Search code examples
javascriptreactjsreact-state-managementreact-state

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) {
        //append to array
        this.setState({
            [path]: this.state.[path].concat([value])
        })
    } else {
        //remove from array
        this.setState({
            [path]: this.state.[path].filter(function (val) {
                return val !== value
            })
        })
    }
}

I know how to dynamically set and get a key in state, but when I try and do

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

I get the below error:

error Image

Any help would be greatly appreciated, Thanks


Solution

  • 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 array
            this.setState(prevState => ({
                [path]: prevState[path].concat([value])
            }))
        } else {
            //remove from array
            this.setState(prevState => ({
                [path]: prevState[path].filter(function (val) {
                    return val !== value
                })
            }))
        }
    }