Search code examples
javascriptreactjsreact-hookssetstate

How to append multiple values in setstate for array object Reactjs


I want to append objects in my array using setState function. My initial variable looks like this:

columns1: [
        {
          title: "Sr. No.",
          render(text, record, index) {
            return {
              children: <div> {index + 1}</div>,
            };
          },
        },
        {
          title: "Account ID",
          dataIndex: "Accountid",
        },
        {
          title: "Alias",
          dataIndex: "Alias",
        },
      ],

Now, in a function I want to add 2 more objects in columns1:

const projCol = {
      title: "Projected Cost",
      dataIndex: "forecast_amount",
      key: "forecast_amount",
  },

  const projChange = {
          title: "Percentage Change",
          dataIndex: "%change",
          key: "%change",
   }

if I only wanted to add projCol I can do

this.setState((prevState) => {
      return {
        columns1: [...prevState.columns1,projCol],
      };
    });

but how can I add both projCol and projChange?


Solution

  • Just add one more element to the array like you do with projCol, separated by commas.

    this.setState((prevState) => {
          return {
            columns1: [...prevState.columns1, projCol, projChange]
          };
      });