wants to add new objects in table in react js

I have a table, it's first three rows are hardcoded. After first three rows I want to add new objects in table. I write code for it but when I enter new data my old data is erase from table and new data is appear. I want it at its place and wants to add new data exactly after it. Here is the code of my state

constructor(props)
{
    super(props)
    {   

        this.state={
            id:'',
            name:'',
            birth:'',
            data:[
                {
                id:'1',
                name:'Muhammad Ali jinnah',
                dateofBirth:'1876'
                },
                {
                    id:'2',
                    name:'Allama Iqbal',
                    dateofBirth:'1877'
                },
                {
                    id:'3',
                    name:'Ahmad Bilal',
                    dateofBirth:'1992'
                }
            ],

        }
    }

in that state i have array of objects i have hardcoded and state for data which i used to get data from my input box..input box are used to get data from user and add data in table and submit used to add data in table by using function..

here is code for my handle submit where i want to setstate for new object

 handleSubmit(event) {
    console.log('A ID:name and birth was submitted: ' + this.state.id,this.state.name,this.state.birth);
    const { id, name, birth } = this.state;    
    const newdata = {
      id: id,
      name: name,
      dateofBirth: birth 
    };

    this.setState(prevState => ({
      data: [prevState.data,newdata ]
    }));
    console.log("new array",this.state.data)
    event.preventDefault();
  }

I want to change its state but i also want my first three rows as i hardcoded

4 answers

  • answered 2018-04-14 14:19 alowsarwar

    Following is the pseudo code that should solve your issue.

    const prevData = this.state.data;
    // Make first 3 are not overridden
    var preserved = prevData.splice(3)
    preserved.push(...newData)
    this.setState({ data : preserved});
    

  • answered 2018-04-14 14:19 Seth McClaine

    If I'm understanding correctly... You should be able to create a render with 3 static rows, then dynamically append rows based on the object you have in state (this.state.data). See below for example.

    render {
        return (
            <table>
                <tr><td>sample1</td></tr>
                <tr><td>sample2</td></tr>
                <tr><td>sample3</td></tr>
                {
                    this.state.data.map((dataElement) => {
                        <tr><td>{dataElement.name}</td></tr>
                    });
                }
            </table>
        )
    }
    

  • answered 2018-04-14 14:19 Pinki Gupta

    let temp=this.state.data; temp=data.push(newdata)

    Add these lines into your handleSubmit() and set temp into your state by using setState method.

  • answered 2018-04-14 14:19 Boy With Silver Wings

    The error is occurring because you are not using the spread operator for inserting into the array.

    When you use something like:

    this.setState(prevState => ({
      data: [prevState.data,newdata ] //This is wrong
    }));
    

    prevState.data becomes the first element of new array and new data becomes the second, instead you can use the spread operator for new array like:

    this.setState(prevState => ({
      data: [...prevState.data,newdata ]
    }));
    

    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          id: "",
          name: "",
          birth: "",
          data: [
            {
              id: "1",
              name: "Muhammad Ali jinnah",
              dateofBirth: "1876"
            },
            {
              id: "2",
              name: "Allama Iqbal",
              dateofBirth: "1877"
            },
            {
              id: "3",
              name: "Ahmad Bilal",
              dateofBirth: "1992"
            }
          ]
        };
        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }
      handleInputChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;
    
        this.setState({
          [name]: value
        });
      }
      handleSubmit(event) {
        console.log('A ID:name and birth was submitted: ' + this.state.id,this.state.name,this.state.birth);
        const { id, name, birth } = this.state;    
        const newdata = {
          id: id,
          name: name,
          dateofBirth: birth 
        };
    
        this.setState(prevState => ({
          data: [...prevState.data,newdata ]
        }));
        console.log("new array",this.state.data)
        event.preventDefault();
      }
      render() {
        return (
          <main>
            <form onSubmit={this.handleSubmit}>
              <input name='id' type='number' value={this.state.id} onChange={this.handleInputChange} placeholder='ID' />
              <input name='name' value={this.state.name} onChange={this.handleInputChange} placeholder='Name' />
              <input name='birth' type='date' value={this.state.birth} onChange={this.handleInputChange} placeholder='Date of Birth' />
              <button type='submit'>Add New</button>
            </form>
            <table className='content'>
              <tbody>
              {
                this.state.data.map(item=>{
                  return (
                    <tr>
                      <td>{item.id}</td>
                      <td>{item.name}</td>
                      <td>{item.dateofBirth}</td>
                    </tr>
                  );
                })
              }
              </tbody>
            </table>
          </main>
        );
      }
    }
    ReactDOM.render(<App />, document.getElementById("root"));
    <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="root"></div>