javascript - How to use onClick with divs in React.js -
i'm making simple application can click on square divs change color white black. however, i'm having trouble. i'd use onclick function allow user click on square change color, doesn't seem working. i've tried using spans , empty p tags, doesn't work either.
here 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 link small project on codepen. http://codepen.io/anfperez/pen/rorkge
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 </div> </div> ); } }); reactdom.render(<box />, document.getelementbyid('div1')); reactdom.render(<box />, document.getelementbyid('div2')); reactdom.render(<box />, document.getelementbyid('div3'));
and in css, delete styles have , put this
.box { width: 200px; height: 200px; border: 1px solid black; float: left; }
you have style actual div calling onclick
on. give div classname , style it. remember remove block rendering app
dom, app not defined
reactdom.render(<app />,document.getelementbyid('root'));
Comments
Post a Comment