Search code examples
jsonreactjsreact-bootstrap-table

Unable to add new key-value pair dynamically to a STATE JSON Array in React App


I am trying to add a new key-value pair to the already loaded JSON Array. I am adding the new key-value pair to customize the header column cells in react bootstrap table but getting the below errors. Can any one please help?

enter image description here

'Columns' in the below state is where I wanted to add new key-value pair

state = {
        data: MYResult.Products || [],
        actualData: MYResult.Products || [],
        columns: MYResult.ParametricList_Attributes || [],
        isCompareClicked: false,
        isDisabled: true,
        selected: []
    };

This is how I am adding the key-value pair -

componentDidMount(){


        checkbox = (column, colIndex) => {
            return (
                <h5>{ column.text }<checkbox/></h5>
            );
        }
        console.log(this.state.columns) ;
        newColumn = this.state.columns.map((column) => {

            return {...column, headerFormatter: checkbox};
        });
        this.setState({columns: newColumn });
    }

Full code here - https://codesandbox.io/s/o1r988qkz Please uncomment the componentDidMount() to see the issue


Solution

  • Firstly, there's a typo in dcolumn and column. And regarding the not defined error, you need to define it using const. Use like:

    const checkbox = (column, colIndex) => {
          return (
            <h5>{column.text}<checkbox /></h5>
          );
        }