Change Background Color of a react tag when clicked

Asked
Active3 hr before
Viewed126 times

6 Answers

clickedbackgroundcolorreactchange
90%

Stack Overflow Public questions & answers ,Connect and share knowledge within a single location that is structured and easy to search., site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.1.40116 ,Join Stack Overflow to learn, share knowledge, and build your career.

However, as for your problem, you need to use the state to change the color of the DIV. Below is the code (Only the modified part is included.)

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      bgColor: ""
    }
  }


  boxClick = (e) => {
    this.setState({
      bgColor: "red"
    })
  }

  render() {
    return (
      <div className="App">


        <article className='experimentsHolder'>
          <h2>Test 3</h2>
          <p>This is an example of an onClick event 'renderd' by react.</p>
          <div className="boxClickCss" 
          style={{backgroundColor: this.state.bgColor}}
           onClick={this.boxClick}>Click Me!</div>
        </article>

      </div>
    );
  }
}
load more v
88%

Html
<div id="app"></div>

Css
button{
  width: 80px;
  height: 40px;
  margin: 15px;
}
.blackButton{
  background-color: black;
  color: white;
}

.whiteButton{
  background-color: white;
  color: black;
}

React
class Test extends React.Component {
  constructor(){
         super();

         this.state = {
              black: true
         }
    }

    changeColor(){
        this.setState({black: !this.state.black})
    }

    render(){
        let btn_class = this.state.black ? "blackButton" : "whiteButton";

        return (
             <div>
                 <button className={btn_class}
                         onClick={this.changeColor.bind(this)}>
                           Button
                  </button>
             </div>
        )
    }
}

ReactDOM.render(<Test />, document.querySelector("#app"))
72%

This is a template about changing the background color of a button in reactjs

how to implement this when we map over an array of buttons. Like

categories.map((category,index) => (
                            <Button 
                                onClick = {() => handleCategoryButtonClick()}
                                className = {buttonState ? 'categoryButtonTrue': 'categoryButtonFalse'}
                                key = {index}
                                title = {category} />
load more v
65%

There are various ways of changing the background color of a React component, two of which we’ll explore: importing a CSS file and using inline styles.,The next approach to changing the background color in React is to write all of the CSS styles inline. ,This isn’t necessarily a method for changing the background color in a React component as it piggy-backs on inline-styles, but it is incredibly useful to learn.,Again, there are some slight differences when writing inline CSS inside of a React component:

<!DOCTYPE html>
<html lang="en-US">

<head>
   <meta charset="UTF-8">
   <title>Test</title>
   <link rel="stylesheet" type="text/css" href="styles.css" />
</head>

<body>
   ...
</body>

</html>
load more v
75%

The approach I am taking is to update the state for that component so that the button is re-rendered with a different background color. How is this actually done?,Glad you got it working, but now I’m confused as to why this works without .bind(this)-ing the handleClick function? I just completed the Leaderboard assignment, and none of my functions that needed a reference for this worked at all without binding them?,Since I am unable to post the codepen link for whatever reason-here is the code,@Faizahmadfaiz’s answer should work just fine. Here is also another way that I’ve used, basically setting CSS conditionally in the render function based on the current state. In the render function something like:

Here is the code:

 var ActionBox = React.createClass({ 

 showMyNumbers: function(){
  if(this.props.pears === "default")
    {console.log("This is in the default configuration")}
    else{console.log("This is in some other configuration")}
  },

  render: function() {
   return(
     <div id="actionBox" onClick={this.showMyNumbers}>
       </div>
   );
 }, 
});

var ApplicationGrid = React.createClass({  

  render: function() {
   var row = [];
   for(var j=0; j<30; j++){
     for(var i=0; i<30; i++){
       row.push(<ActionBox myRowNumber={j} myColumnNumber={i} pears = {this.props.oranges}/>);
      }
   }
    return(
     <div id="applicationGrid">
        {row}
      </div>
    );
  }, 
});

var ButtonsAndGrid = React.createClass({ 



  getInitialState: function() {
    var defaultcolor1 = document.getElementById(btn1).style.backgroundColor;
    return {
      btn1Bckground: defaultcolor1,
    };
  },

  changecolor() {
        this.setState({
      btn1Bckground: "lightblue"
   });
    },

  componentDidMount() {
      this.refs.button1.addEventListener('click', this.changecolor);
     
   },


  render: function() {

    return(
   <div>
   <div id="buttonsDiv">
  
     <button type="button" ref="button1" className="normalBtn" id="btn1" onClick={this.props.plethora} >This works</button>
  
     </div>
   <ApplicationGrid oranges = {this.props.apples} />
    </div>
    );
 }, 
});

var MyApp = React.createClass({  


 getInitialState: function() {

   return {
     startingConfiguration: "default",
    };
  },


 doSomething: function(evt) {
   this.setState({
     startingConfiguration: "other"
    });
  },

 render: function() {
  return(
    <div id="mainDiv" >
  <h1> Game of Life! </h1>
    <ButtonsAndGrid apples={this.state.startingConfiguration} plethora={this.doSomething}/> <Footer />
    </div>
    );
  }, 
});

var Footer = React.createClass({
  render() {
   return (
    <footer>
      <div id="containerfooter">
          <p>Written by <a href="http://codepen.io/profaneVoodoo/full/dXBJzN/">John Gillespie</a> for FreeCodeCamp Campers (and also to impress my kids). Happy Coding!</p>
        </div>
      </footer>
    );
  }
  });

ReactDOM.render(
  <MyApp />  ,
  document.getElementById('GoL')
);
load more v
40%

We wrap the <Router /> component inside a div, which is the main element that has the backgroundColor key in its style prop.,We need to install react-router-dom for this example, so run the following command in the command-line utility.,In this guide, we learned to change the background color of the route by storing the colors in the state and manipulating it by the onClick handler using React hooks. I hope you have a good sense of React hooks after reading this guide.,In the main component, the color property changes according to the current route. The mapping of colors is as follows:

1function Index() {
2  return (
3    <>
4      <h2>Home</h2>
5      <p>This is the Home Page</p>
6    </>
7  );
8}
9
10function About() {
11  return (
12    <>
13      <h2>About</h2>
14      <p>This is the About Page</p>
15    </>
16  );
17}
18
19function Users() {
20  return (
21    <>
22      <h2>Users</h2>
23      <p>This is the Users Page</p>
24    </>
25  );
26}
load more v

Other "clicked-background" queries related to "Change Background Color of a react tag when clicked"