1

I have a state:

this.state = {
    rowData
}

rowData = [
    {MEMBER: "DATA1", ALIS: "DATA2", STATUS: "DATA3"},
    {MEMBER: "DATA1", ALIS: "DATA2", STATUS: "DATA3"},
    {MEMBER: "DATA1", ALIS: "DATA2", STATUS: "DATA3"}
]

On a button click, I want to be able to add an empty object like this.

   rowData = [
        {MEMBER: "", ALIS: "", STATUS: ""},   //CLICK 1
        {MEMBER: "", ALIS: "", STATUS: ""},   // CLICK 2 and so on
        {MEMBER: "DATA1", ALIS: "DATA2", STATUS: "DATA3"},
        {MEMBER: "DATA1", ALIS: "DATA2", STATUS: "DATA3"},
        {MEMBER: "DATA1", ALIS: "DATA2", STATUS: "DATA3"}
    ]

How can I update the state to include empty strings on button clicks.

1 Answer 1

4

You can use the spread operator:

this.setState({
  rowData: [
    { MEMBER: "", ALIS: "", STATUS: "" },
    ...this.state.rowData
  ]
})

For example:

const rowData = [
  { MEMBER: "DATA1", ALIS: "DATA2", STATUS: "DATA3" },
  { MEMBER: "DATA1", ALIS: "DATA2", STATUS: "DATA3" },
  { MEMBER: "DATA1", ALIS: "DATA2", STATUS: "DATA3" }
];

class MyComponent extends React.Component {
  state = {
    rowData
  };

  handleClick = () => {
    this.setState({
      rowData: [
        { MEMBER: "", ALIS: "", STATUS: "" },
        ...this.state.rowData
      ]
    });
  };

  render() {
    return (
      <>
        <button onClick={this.handleClick}>Button</button>
        {this.state.rowData.map(({ MEMBER, ALIS, STATUS }, i) => (
          <p key={i}>
            Member: {MEMBER}, Alis: {ALIS}, Status: {STATUS}
          </p>
        ))}
      </>
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.