Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native set style as State

I want to use backgroundColor of style1 as a state, and change it in the function change().
How can I access style1?

My point is to call the function change from another function, making the button change its color to yellow, then change it's colour to blue again after sometime.

export default class App extends Component{ 
  constructor (props){
    super(props);
    this.state = {
      //style1.backgroundColour: blue  //? Can't 
    }
    this.change=this.change.bind(this)
  }

  change() {
    this.setState({ style1.backgroundColour: yellow }) //?
  }

  render(){
    return (
      <View style={styles.style1} > </View>

    );
  }
}

const styles = StyleSheet.create({

  style1:{
    padding: 5,
    height: 80,
    width: 80,  
    borderRadius:160,    
    backgroundColor:'blue',
  },

});
like image 910
Shiranox Avatar asked Sep 18 '25 19:09

Shiranox


1 Answers

Update: This question and my answer was based on class components. But functional components and hooks are the current way of using React for a long time now.

First you should create a state for your backgroundColor:

const [backgroundColor, setBackgroundColor] = useState('blue');

then change it's value in your function

setBackgroundColor('yellow');

and finally, use it in style prop:

style={[styles.style1, {backgroundColor}}

Old answer, using class components

You can give an array to style prop. So you can put any other styles from another sources.

First you should declare a default value for your backgroundColor state:

this.state = {
  backgroundColor: 'blue',
};

then set it's state in your function as normal string state:

this.setState({backgroundColor: 'yellow'});

and finally, use it in style prop:

style={[styles.style1, {backgroundColor: this.state.backgroundColor}]}
like image 52
Ugur Eren Avatar answered Sep 21 '25 08:09

Ugur Eren