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

Activate the div when hovering over the span

Experiencing an issue with triggering a visible div while hovering over a span. Here is the code structure: <ul class="products"> <li> <a href="somelink"> <img src="some image"> <div class="overlay"> Some Text</div> & ...

Looking to make an API call with every keystroke in a React application, however, the response may contain a large number of objects

Currently, I am utilizing react and axios for the frontend while relying on nextjs with prisma for the backend. Within my database, there are 4000 exercises related to fitness stored as data. My objective is to create a function where each keystroke trigge ...

Is it achievable to modify the appearance of the "Saved Password" style on Firefox?

After creating a login page that initially had a certain aesthetic, I encountered an issue when saving login data in Firefox. The saved login page took on a yellow-ish tint that was not present in my original design: I am now seeking advice on how to remo ...

The JSON parser encountered an unexpected end while parsing near the section related to "jscs" and "moch"

I seem to be facing an issue with npm. I attempted to run the command npx create-react-app my-app but encountered an error. Here is the output from my command prompt: c:\Users\sysli\Desktop\reactprojects>npx create-react-app my-app ...

Encountering the error message "TypeError: Unable to access properties of null (reading 'get')" while utilizing useSearchParams within a Storybook file

Looking at the Next.js code in my component, I have the following: import { useSearchParams } from 'next/navigation'; const searchParams = useSearchParams(); const currentPage = parseInt(searchParams.get('page') || '', 10) || ...

Manipulating the location where a dropdown menu intersects with a button

Is there a way to adjust the drop-down menu positioning so that it aligns with the button on the top right side of the menu pop-up, rather than the top left as it currently does? Below is the code I have borrowed from an example on W3Schools. .dropbtn ...

Tips for including a for loop within a return statement in React Native

I'm having trouble displaying multiple content on the screen using a for loop. The map method doesn't seem to work for me because I don't have an array. Here's what I've attempted: {() => { for (let i = 0; i < cart ...

How can I incorporate the 'client' application into the 'loading.js' file?

I implemented a Lottie component in my loading.js file. Utilizing the App router (Next13). This is the code for the lottie component: import { Player } from '@lottiefiles/react-lottie-player'; import LoadingLottie from '@/assets/loading.j ...

I encountered an issue when trying to include the dotenv file, receiving the following error message: [TypeError: Network request failed]

babel.config.js File plugins: [ ["module:react-native-dotenv", { "envName": "APP_ENV", "moduleName": "@env", "path": ".env", "blocklist": null, "allowlist": null, "blacklist": null, // DEPRECATED "whitelist": ...

Can you provide a tutorial on creating a unique animation using jQuery and intervals to adjust background position?

I am attempting to create a simple animation by shifting the background position (frames) of the image which serves as the background for my div. Utilizing Jquery, I aim to animate this effect. The background image consists of 6 frames, with the first fr ...

Redux and React: Uncaught Error (TypeError): Unable to access the 'push' property because it is undefined

I'm encountering an issue in my Redux action file code where I am trying to use history.push('/userfeed') after a successful user login. However, I keep running into the error message: Unhandled Rejection (TypeError): Cannot read property &a ...

I am in need of help with coding so that my entire webpage is displayed properly even when I resize it to the smallest width. Additionally, I need assistance with making

Having some issues with making my personal website work correctly. I'm planning to share images of how it looks at different widths - largest width and smallest width. Also, here are the links to my website here and to my GitHub code here Seeking gui ...

Creating a pop-up effect for a div in the center of a table cell using HTML and CSS

I am currently working with Angular and facing a challenge where I need to display a div like a popup in a table cell when clicked. Despite having the click event logic in place, I am unsure of how to achieve this without using external libraries such as B ...

What is the best way to activate a function when the route is changed?

Exploring My Routes: <Provider store={store}> <Router> <Fragment> <Navbar /> <Switch> <Route exact={true} path="/" component={Landing} /> <Route exact={true} path="/reg ...

What is the best way to implement the Active list element feature in my menu bar?

The current list element is : <li class="nav__item"><a class="nav__link nav__link--active " href="#"... The standard list element is: <li class="nav__item"><a class="nav__link " href=&quo ...

Closing a batch file after the React app is shut down can be achieved by utilizing a

Running my react application involves the use of a .bat file with the following commands: cd.. cd projects cd material cd server npm run dev Upon executing this script, it initiates cmd and launches my app in Chrome. Despite spending hours searching for ...

Create an input box with a designated class

When I click the button in my HTML and JavaScript code below, I am able to dynamically add a text field and radio button. This functionality is working properly. However, I also want the newly generated text field to have the same font size and appearance ...

Transitioning to Material-ui Version 4

During the process of upgrading material-ui in my React Application from version 3.9.3 to version 4.3.2, I encountered an error message stating TypeError: styles_1.createGenerateClassName is not a function. I am feeling lost when it comes to transitioning ...

Is there a way to ensure the collapsible item stays in its position?

I'm encountering an issue with the display of items within collapsible cards. Here is what it currently looks like: And this is how I want it to appear: Is there a way to achieve the desired layout using Bootstrap's Grid or Flex Layout? Here i ...

I'm unable to adjust the font size of the final h3 element

I'm currently designing a webpage with various titles, but I've encountered an issue. I am unable to adjust the font size of the last h3 title without affecting the rest of the titles. I'm curious as to why this is happening and how I can re ...