Is there a way to adjust the background hues of a React component when a click event is triggered?

Currently, I have 3 React components that each consist of a div element. When I click on one component, I want to change its background color to black. If I then select another component, the previously selected component should return to its normal background color. What is the best way to accomplish this dynamic behavior?

Answer №1

Here's an uncomplicated solution:

.App {
  display: flex;
}

.box {
  width: 150px;
  height: 150px;
  margin: 20px;
  padding: 20px;
}
import React from "react";
import "./styles.css";

export default function App() {
  const [bg, changeBGColor] = React.useState(1);
  return (
    <div className="App">
      <div
        className="box"
        onClick={() => changeBGColor(1)}
        style={{
          backgroundColor: bg === 1 ? "black" : "red"
        }}
      />
      <div
        className="box"
        onClick={() => changeBGColor(2)}
        style={{
          backgroundColor: bg === 2 ? "black" : "yellow"
        }}
      />
      <div
        className="box"
        onClick={() => changeBGColor(3)}
        style={{
          backgroundColor: bg === 3 ? "black" : "green"
        }}
      />
    </div>
  );
}

Copy and paste this code into Codesandbox to view the result.

In this example, I'm utilizing a React hook that takes a unique id as input. If set, the corresponding component will appear in black.

Therefore, the first div is initially black. When I click on the second div, the value of bg changes to 2 and in the style, I check if 2 is selected then set the color to black. The same process applies to the third div.

Answer №2

If each of those elements possess their distinctive characteristics (or if they do not, you should include them), you are able to adjust their className using className={this.state.selectedComponent==="uniqueID" ? "activeClassName" : ""}, while also having a state attribute (selectedComponent) that is assigned with the unique property upon onClick event.

Answer №3

import React, { Component } from 'react'

export default class CustomComponent extends Component {
  constructor(props) {
    super(props)
    this.state = {
      background: 'blue'
    }
    this.changeBackground = this.changeBackground.bind(this)
    this.changeBackground2 = this.changeBackground2.bind(this)
  }

  changeBackground() {
    this.setState({
      background: 'yellow'
    })
  }

  changeBackground2() {
    this.setState({
      background: 'purple'
    })
  }

  render() {
    return (
      <div style={{ backgroundColor: this.state.background }}>
        <button onClick={this.changeBackground} />
        <button onClick={this.changeBackground2} />
      </div>
    )
  }
}

This method provides a basic way to customize the background color of a div element. Initially set to blue, clicking the first button changes it to yellow and the second button to purple.

This concept can be applied for various purposes in your projects.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The ReactJS Application Cache Client fails to display the most recent updates

One issue I'm currently facing is with my application in production. Some clients have reported that they are unable to see the new changes unless they clear their cache completely. Using Techs: React Any suggestions on what steps I should take to a ...

Is Material UI available for React without any cost?

Just wondering, is Material UI (for a react application) free to use? We're considering implementing it in our app, but want to make sure there are no licensing complications. Appreciate any guidance you can provide. Thanks! ...

What are some effective methods for addressing security flaws such as Regular Expression Denial of Service (Re

My react project is showing some vulnerabilities when I run it. Here is the link to image containing the vulnerability report: Can someone guide me on how to fix these vulnerabilities? Also, could you please explain what this warning means and if updating ...

Hide elements on desktop viewport using media queries

If you want to see the code I'm using on my live site, visit www.randolphlibrary.org/mobilesite.htm In short: How can I implement a list-view style for users with a viewport of max-width 768px so that it caters to mobile users? My plan was to add th ...

The navigation bar and text subtly shift when displayed on various devices or when the window size is adjusted

Hello, I am brand new to web development and have encountered an issue on my website. Whenever the window is resized or viewed on a different screen, the navigation bar (which consists of rectangles and triangles) and text elements start moving around and ...

Images are not visible when scrolling horizontally

Hello everyone, this is my first time reaching out with a question here! I've been working on setting up a horizontal scroll feature and I'm almost there, but I'm encountering an issue where the scroll bar is appearing at the bottom of the ...

Disable Chrome's suggestions bar on your Android phone

I'm having trouble disabling spelling suggestions for an input box and everything I've tried so far hasn't worked. I've already used attributes like autocomplete="off", autocapitalize="off", and spellcheck="off" for the input field, bu ...

Error in React Native JS: Cannot call the `map` function on variable `l`

Recently diving into the world of Js and React, I am tasked with creating an application for Macronutrients in my second semester project. The challenge I'm facing is incorporating a Pie Chart that displays the values from my state. To implement the ...

I am interested in modifying the color of the tick marks on the input[range] element

Seeking Slider Customization Help I am eager to learn how to create and personalize a slider using HTML. Although many resources offer guidance on customizing the slider itself, I have yet to come across any information on customizing the scale. For insta ...

Tips for eliminating the default margin without using a float

Exploring the world of divs and buttons led me to an interesting discovery: removing a float creates a natural margin. Upon entering this styling: body { background: gray; } button { font-size: 17px; color: white; margin-l ...

Can someone help me troubleshoot why my multi-step form is not functioning properly?

I've been working on a multi-phase form, but it's not behaving as expected. I've tried different code variations, but for some reason, it's not functioning properly. After spending two days on it, I'm starting to feel a bit frustra ...

JavaScript-enhanced HTML form validation

I encountered a small glitch while working on simple form validation with JavaScript. I tried to catch the issue but have been unable to do so. Here is the code snippet, where the problem lies in the fact that the select list does not get validated and I ...

Tips for implementing the data.map function in Reactjs

I am currently exploring Reactjs with nextjs, and I am facing an issue with fetching data using the "map" function. Can anyone provide guidance on how to approach this? Below is my current code snippet: import { useEffect, useState } from "react" export ...

Tips for including multiple spaces within a cell of a table

I've come across an issue while working on a table and attempting to insert text with multiple spaces. For example, I want to add the text HELLO<1stSPACE><2ndSPACE>WORLD. However, when I enter it as HELLO WORLD, it only displays with a si ...

UI and `setState` out of sync

Creating a website with forum-like features, where different forums are displayed using Next.js and include a pagination button for navigating to the next page. Current implementation involves querying data using getServerSideProps on initial page load, f ...

What is the reason behind the continual change in the background image on this website?

Can you explain the functionality of this background image? You can find the website here: ...

Are you searching for a stylish tabbed navigation menu design?

I am searching for a tabbed navigation menu specifically designed to showcase images as the tab items. Here is an example of what I have in mind: <div class="menu"> <a href="#"> <img src="images/Chrysanth ...

Unique hover effects for tab navigation

I have designed my website with 4 tabs on the homepage: holidays, hospitality, events, and consulting. I am trying to create an effect where hovering over the tabs displays images. Here is the code I have tried: HTML: <div class="menu_links"> & ...

What are the reasons behind professional web designers opting for absolute paths over relative paths (like for CSS, Javascript, images, etc.)?

It used to be my belief that everyone utilized relative paths, like /styles/style.css. However, I've noticed that certain renowned web designers (such as and ) prefer absolute paths (http://example.com/styles/style.css). This begs the question - why ...

Tips for utilizing the font-family style to span multiple columns

I recently discovered that you can set the background color across table columns using the <colgroup> tag. table { border: 2px solid; border-collapse: collapse; } td { border: 2px solid; } <ta ...