Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Js, adding new object to an array [duplicate]

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>
      );
  }
}
like image 543
mohan Avatar asked Feb 22 '18 07:02

mohan


People also ask

How do you add an object into an array in React?

Use the spread syntax to push an element into a state array in React, e.g. setNames(current => [... current, 'Carl']) . The spread syntax (...) will unpack the existing elements of the state array into a new array where we can add other elements.

How do you repeat an element in React?

Using the Array map function is a very common way to loop through an Array of elements and create components according to them in React. This is a great way to do a loop which is a pretty efficient and is a tidy way to do your loops in JSX.

How do you prevent duplicates in React?

To remove the duplicates from an array in React, pass the array to the Set constructor, e.g. [... new Set(arr)] . Each value in a Set has to be unique, so any duplicates get automatically removed.

Can array have duplicate values JavaScript?

With ES6, we have a javascript Set object which stores only unique elements. A Set object can be created with array values by directly supplying the array to its constructor. If the array has duplicate values, then they will be removed by the Set. This means that the Set will only contain unique array elements.


1 Answers

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);       
}
like image 50
Gorka Hernandez Avatar answered Sep 25 '22 18:09

Gorka Hernandez