How to use onClick with divs in React.js How to use onClick with divs in React.js javascript javascript

How to use onClick with divs in React.js


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'));


For future googlers (thousands have now googled this question):

To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.

These are right:

<div onClick={doThis}><div onClick={() => doThis()}>

These are wrong:

<div onClick={doThis()}><div onClick={() => doThis}>

(and don't forget to close your tags... Watch for this:

<div onClick={doThis}

missing closing tag on the div)


Your box doesn't have a size. If you set the width and height, it works just fine:

var Box = React.createClass({    getInitialState: function() {        return {            color: 'black'        };    },    changeColor: function() {        var newColor = this.state.color == 'white' ? 'black' : 'white';        this.setState({            color: newColor        });    },    render: function() {        return (            <div>                <div                    style = {{                        background: this.state.color,                        width: 100,                        height: 100                    }}                    onClick = {this.changeColor}                >                </div>            </div>        );    }});ReactDOM.render(  <Box />,  document.getElementById('box'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id='box'></div>