Skip to content Skip to sidebar Skip to footer

React Native: You Attempted To Set The Key On An Object That Is Meant To Be Immutable And Has Been Frozen

I am new to react native and was creating my first. In my add I decided to change the backgroundColor of my App dynamically for which I did something like this let style = StyleS

Solution 1:

Something you should know about Stylesheet:

  • When you do Stylesheet.flatten, it will flatten arrays of style objects one immutable style object.
  • When you do Stylesheet.create, it will generate an immutable style object.

But why does it have to be immutable?

Refer the documentation, in order to increase the performance, the immutability of the style object will enable a simpler communication between the UI and JS Thread. In other words, they will just use the IDs of the style objects to communicate with each other through the native bridge. So, the object can't be mutated.

The solution to this problem is just as simple as this:

  • Using an array of styles.
  • Updating the styles dynamically using state.

Below is the code demonstrating how to do it:

classAppextendsReact.Component {

  state = {
    clicked: false
  }

  handleOnPress = () => {
    this.setState(prevState => ({clicked: !prevState.clicked}))
  }

  render() {
    return (
      <Viewstyle={[styles.container, {backgroundColor:this.state.clicked ? "blue" : "red"}]}><ButtononPress={this.handleOnPress}title="click me" /></View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Here is the Snack Expo link of the code: https://snack.expo.io/SJBLS-1I7

Post a Comment for "React Native: You Attempted To Set The Key On An Object That Is Meant To Be Immutable And Has Been Frozen"