Skip to content Skip to sidebar Skip to footer

How To Dynamically Get State Array Name React

How can I dynamically set the name of the array in state, to get it from state. onCheckBoxItemClickList(e, value, path) { console.log(e.target.checked) if (e.target.checked

Solution 1:

You have an extra dot in your code (after state):

[path]: this.state.[path].concat([value])

Should be:

[path]: this.state[path].concat([value])

Then whenever you want to set the state based on the previous state, you should use the setState which takes a callback in, with the prevState as argument.

So your code should look something like:

onCheckBoxItemClickList(e, value, path) {
    console.log(e.target.checked)
    if (e.target.checked) {
        //append to arraythis.setState(prevState => ({
            [path]: prevState[path].concat([value])
        }))
    } else {
        //remove from arraythis.setState(prevState => ({
            [path]: prevState[path].filter(function (val) {
                return val !== value
            })
        }))
    }
}

Post a Comment for "How To Dynamically Get State Array Name React"