State is the base part of react native application, because there are commonly 2 types of data that controlled every component in react native application – Props and States. You can read more about Props here on my this tutorial. State is used for dynamic data or the data which is going to Change or Update in react native application. So in this tutorial we would going to learn about basic declaration structure of State and also How to change-Update value of State on button click using function and also Use State Inside React Native App fully explained tutorial, So let’s get started .
Topics we would cover in this tutorial is :
- How to declare State in react native app.
- Create String type, Integer type and Boolean type State.
- How to Update State value using setState({ }) method .
- How to Set-Call state value in anywhere( Text Component ).
Contents in this tutorial How to Use State Inside React Native App Fully Explained:
1. How to declare State in react native app and Assign a Value to it :
The State is declared or created inside the constructor() of application class. We need to set a scope inside constructor() ,Now we need to use the this.state={} method to declare state. In below code we would create a State named as SampleStateTemp and assign a String value to it. For example see the below code :
1
2
3
4
5
6
7
8
9
10
|
constructor(){
super();
this.state={
SampleStateTemp : “Sample Value”,
}
}
|
2. Create String type, Integer type and Boolean type State :
As you see in above code we have learn about basic declaration and value assign structure of State. Now we would create State 3 different type of States using above structure. We would going to create String, Integer and Boolean type of States.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
constructor(){
super();
this.state={
SampleState1 : “Hello World”,
SampleState2 : true,
SampleState3 : 1234,
}
}
|
3. How to Update State value using setState({ }) method :
State gives us its inbuilt method known as setState({ }) to update-change the value of already initialized state. As you can see in below code we would updating all of 3 states value using setState({ }) method.
1
2
3
4
5
|
this.setState({ SampleState1 : “New Text” });
this.setState({ SampleState2 : false });
this.setState({ SampleState3 : 4321 });
|
4. How to Set-Call state value in anywhere( Text Component ) :
This step is very important because now we would know about calling a state value and using the State value at anywhere in our class. Now as you can see in below code we would call the state value anywhere in our program usign this.state.YourStateName structure. If you want to Show or Hide any component using State value using then read my this tutorial.
1
|
<Text style={Put Your Style Class Here} > {this.state.SampleState1} </Text>
|