Categories
react-native react-redux react-router reactjs

React Js, adding new object to an array

I have a text field and a radio button.

I am making an object of these two values and putting inside an array, so that i can store this in Mongo DB.

I am constructing an array of objects and trying to iterate for showing the details in a table.

Not able to displaying the details.

Help needed for this.

 export class AddColumns extends React.Component{
constructor(props) {
super(props);
this.state={
newItemInput: '',
selectedValue: '',
buyItems :[],
object : {}
}
}
handleChange=(event)=> {
this.setState({
...this.state,
selectedValue: event.target.value
});
};
change (event){
this.setState({
[event.target.name]:event.target.value
});
};
addItem(e){
e.preventDefault();
const newItemInput = this.state.newItemInput;
const newRadioValue = this.state.selectedValue;
const obj = {'item':newItemInput, 'columnType':newRadioValue};
this.state.buyItems.push(obj);
console.log(this.state.buyItems);
}
render(){
const {buyItems,message} = this.state;
return (
<div className="container">
<form className="form-inline" onSubmit={(e) => {this.addItem(e)}}>
<div className="form-group">
<label className="sr-only" htmlFor="newItemInput">Add New Item</label>
<input type ="text" ref ={input => this.newColumn = input} name="newItemInput" placeholder="Modules" value = {this.state.newItemInput} className="form-control"
id="newItemInput" onChange={event => this.change(event)}/>
</div>
<div className="k-form-field">
<input type="radio" name="radio" value="radio1" className="k-radio" onChange={this.handleChange}/>
<label className="k-radio-label">RadioButton 1</label>
<input type="radio" name="radio" value="radio2" className="k-radio" onChange={this.handleChange}/>
<label className="k-radio-label">RadioButton 2</label>
<div className="form-group">
<button type="submit" className="btn btn-primary">Add</button><p>{this.state.messgae}</p>
</div>
</form>
<div className="content">
<div>
{
buyItems.map((rowdata,i) => {
<div>
{rowdata.item}
</div>
})
}
</div>
</div>
</div>
);
}
}

For the view to update, you must call setState, and not just push an item to the array, you can easily do it using the spread syntax:

addItem(e){
e.preventDefault();
const newItemInput = this.state.newItemInput;
const newRadioValue = this.state.selectedValue;
const obj = {'item':newItemInput, 'columnType':newRadioValue};
this.setState({
buyItems: [...this.state.buyItems, obj]
});
console.log(this.state.buyItems);
}

An alternative would be create a copy of the old array, push the new item and proceed to set the state:

addItem(e){
e.preventDefault();
const newItemInput = this.state.newItemInput;
const newRadioValue = this.state.selectedValue;
const obj = {'item':newItemInput, 'columnType':newRadioValue};
const newArray = this.state.buyItems.slice(); // Create a copy
newArray.push(obj); // Push the object
this.setState({ buyItems: newArray });
console.log(this.state.buyItems);
}