Leia_Organa Leia_Organa -4 years ago 51
Javascript Question

How to use onClick with divs in React.js

I'm making a very simple application where you can click on square divs to change their color from white to black. However, I'm having trouble. I'd like to use the onClick function to allow a user to click on a square to change its color, but it doesn't seem to be working. I've tried using spans and empty p tags, but that doesn't work either.

Here is the code in question:

var Box = React.createClass({
getInitialState: function() {
return {
color: 'white'
};
},

changeColor: function() {
var newColor = this.state.color == 'white' ? 'black' : 'white';
this.setState({
color: newColor
});
},

render: function() {
return (
<div>
<div
style = {{background: this.state.color}}
onClick = {this.changeColor}
>
</div>
</div>
);
}
});


Here's a link to my small project on CodePen.
http://codepen.io/anfperez/pen/RorKge

Answer Source

This works

var Box = React.createClass({
getInitialState: function() {
    return {
        color: 'white'
    };
},

changeColor: function() {
    var newColor = this.state.color == 'white' ? 'black' : 'white';
    this.setState({ color: newColor });
},

render: function() {
    return (
    <div >
    <div className='box' style={{background:this.state.color}} onClick={this.changeColor}> In here already
    </div>
    </div>
    );
}
});
ReactDOM.render(<Box />, document.getElementById('div1'));

ReactDOM.render(<Box />, document.getElementById('div2'));

ReactDOM.render(<Box />, document.getElementById('div3'));

and in your css, delete the styles you have and put this

.box {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  float: left;
}

You have to style the actual div you are calling onClick on. Give the div a className and then style it. Also remember to remove this block where you are rendering App into the dom, App is not defined

ReactDOM.render(<App />,document.getElementById('root'));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download