Issue
I am trying to create a simple checkbox using reactJS and trying to bind the state of the checkbox using handlecheck()
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
<title>Getting Started with React</title>
</head>
<body>
<div id='react-container'></div>
<script type="text/babel">
class Checkbox extends React.Component{
constructor(props){
super(props)
this.state = {
checked: false
}
this.handleCheck = this.handleCheck.bind(this)
}
handleCheck(){
this.setState ({
checked: true
})
}
render(){
return(
<div>
<input type = "checkbox"/>
</div>
)
}
}
ReactDOM.render(
<Checkbox />,
document.getElementById("react-container")
)
</script>
</body>
</html>
But, here even though I am using
handleCheck(){
this.setState ({
checked: true
})
}
I am still able to check and uncheck the box multiple time, but in reality, it shouldn't as it has to check it once and should stop. I know that in the actual scenario it should be something like:
handleCheck(){
this.setState ({
checked: !this.state.checked
})
}
Can someone tell me why am I able to check and uncheck multiple times even though I am doing it wrong?
Solution
You created a controlled component, which needs a handler to change the state, and it's value/checked properties are controlled by the state.
You need to assign this.handleCheck
as the onChange
handler, and this.state.checked
as the checked
property value:
class Checkbox extends React.Component {
constructor(props) {
super(props)
this.state = {
checked: false
}
this.handleCheck = this.handleCheck.bind(this)
}
handleCheck() {
this.setState({
checked: true
})
}
render() {
return (
<div>
<input
type="checkbox"
checked={this.state.checked}
onChange={this.handleCheck}
/>
</div>
)
}
}
ReactDOM.render(
<Checkbox /> ,
document.getElementById("react-container")
)
<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='react-container'></div>
Answered By - Ori Drori
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.