Maria Jane Maria Jane - 2 months ago 9
Javascript Question

toggle checkbox using react failed

I'm picking up react. But often time I have no clue what's the error. Below code did not render properly, and in the console of jsbin it shows no error.

const App = React.createClass ({
getInitialState() {
return {checked: false}
},
handleCheck() {
this.setState({checked: !this.state.checked})
},
render() {
return(
<div>
<input type="checkbox" onChange={this.handleCheck} />
<p>This box is {this.state.checked}</p>
</div>
)


}
})

ReactDOM.render(<App />,document.getElementById('app-container'));


https://jsbin.com/dehafizaba/1/edit
Need advise.

Answer

It "works fine". The problem is that React doesn't show a string representation of the boolean value. If you output something else it works, e.g.:

<p>This box is {this.state.checked ? 'checked' : 'unchecked'}</p>