Search code examples
react-nativesetstate

react native dynamic setstate with string and dynamic index


react native dynamically generate key1-100 state. A combination of string and dynamic index. But, how can i do that without sytaz error?

this.setstate({ 
     key[index]:1 
})

Solution

  • For React Native to detect changes to state and thus re-render your view you must call setState in immutable manner. So in your case try the following:

    //copy state
    const newState = {...this.state};
    //access property - "key1, key2, etc" whatever index is.
    newState['key'+index] = 1;
    // set new state
    this.setState(newState);