Assign value to 2d array in React/JavaScript

Viewed 156

I am working on a React project where i need a multidimensional constant using useState which stores +/- symbols on some condition.

const [button, setButton] = useState([["+"]]);

and i have the condition something like:


    const handleAddFields = (data_index, index, e) => {
        console.log("aaaaa!!!", data_index)
        console.log("bbbbb!!!",index)
        
        if (button[data_index][index] === "+") {

            const btn = [...button]
            btn[data_index][index] = "-"
            btn[data_index].push(["+"])
            setButton(btn)

            const btnColour = [...btnClass]
            btnColour[index] = "danger"
            btnColour.push("primary")
            setBtnClass(btnColour)

            
        } else {
            const btn = [...button]
            btn.splice(index, 1);
            setButton(btn)

            const btnColour = [...btnClass]
            btnColour.splice(index, 1);
            setBtnClass(btnColour)

            const values  = [...inputFields];
            values.splice(index, 1);
            setInputFields(values);
        }
        
    };

i am getting an error as

Cannot assign to read only property '0' of string '+'
at
btn[data_index][index] = "-"
this line

The Place where the function handleAddFields is called is a button

<Button name="btn" id="button" type="button" color={btnClass[data_index][index]} block onClick={(e) => handleAddFields(data_index, index, e)}>{button[data_index][index]}</Button>

I think React does not allow assigning value to multidimensional array.
What could be the possible solution to this?

1 Answers

Looks like your input is empty, try to assigning it some value

Related