I'm fairly new to react, and I'm trying to create a simple form. The form app has many elements including the 3 checkbox. And to simplify my issue, I'm only showing the checkboxes. Here what I'm doing
- When I click on a checkbox, the value of the label will be pushed into an array and saved into the App state.
- I'm using
event.target.name
because I have multiple inputs in the form and I wanted to keep just in case to make my problem more descriptive. - When I click on submit, it should clear the checkbox.
The problem is when I click on checkbox all the 3 of get checked and it won't be cleared after hitting submit. Is there any way to overcome this? or why its happening?
function CheckBox(props) {
var style= {
padding:10,
marginLeft:5
}
return(
<div style={style} >
{props.checkboxList.map((item,index) =>
<div key={index}>
<input type="checkbox"
onChange={props.changeHandler}
checked={props.checkStatus} name={props.name} value={item.val} />
<label>{item.num}) {item.val}</label>
</div>)}
</div>
)
}
class App extends React.Component{
constructor(props) {
super(props);
this.state={item:[],checked:false}
this.changeHandler=this.changeHandler.bind(this)
this.submitHandler=this.changeHandler.bind(this)
}
changeHandler(event) {
if(event.target.name=="choice") {
var arr=this.state.item.slice()
arr.push(event.target.value)
this.setState({item:arr, checked:event.target.checked}, ()=> console.log(this.state.item +"--"+ this.state.checked))
}
else{ console.log('error')}
}
submitHandler(){
this.setState({item:[],checked:false})
}
render() {
return(
<div>
<CheckBox checkboxList={[
{num:"a", val:"choice 1"},
{num:"b", val:"choice 2"},
{num:"c", val:"choice 3"}]} changeHandler={this.changeHandler} name="choice" checkStatus={this.state.checked} />
<button onClick={this.submitHandler}>Submit</button>
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById("root")
)
<script src="http://ift.tt/2v15cch"></script>
<script src="http://ift.tt/2vktd0h"></script>
<div id="root"></div>
Aucun commentaire:
Enregistrer un commentaire