I am very new to react and am trying to create a checkbox and also display the selected checkbox names list in a textbox. I am using selected[] to store the values for the selected box and checked[] to store whether that box is checked or not.If it is checked I update the value of selected accordingly.
The code as of now works fine but I want to avoid use of forceupdate() and use setState(). When I use I am unable to update the selected[] value using it. Can somebody tell me of how to update the particular array index value using setstate so thatit gets render itself and I do not have to use forceupdate() ?
thank you.
var history = React.createClass({
getInitialState : function(){
return {
checked : [],
selected: []
};
},
componentWillMount : function(){
},
handleChangechk: function (e){
const target = e.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
if(value===true)
{
this.state.checked[name]= true;
this.state.selected[name] = name;
this.forceUpdate();
}
else
{
this.state.checked[name]= false;
this.state.selected[name] = '';
this.forceUpdate();
}
},
render : function() {
var historyList = [];
var selectedList = [];
for (var i = 0; i < 10; i++) {
historyList.push(<span key={i}><input type="checkbox" name = {i} checked={!!this.state.checked[i]} onChange ={(e)=> this.handleChangechk(e)}/><span ></span><label >checkbox {i}</label></span>);
if(this.state.selected[i])
{
selectedList.push(this.state.selected[i]);
}
};
return( /* display selected checkbox (selectedList ); */}});