This tutorial is one of the most basic tutorial in react native. In this tutorial we would going to create a react native app with Text and Button component. Now we would Change Text Component Value Dynamically using State with SetState method on button onPress in Android iOS Example Tutorial.
Contents in this project Change Text Component Value Dynamically on Button Click :
1. Import StyleSheet, View, Button, Platform and Text component in your project.
1
2
3
|
import React, { Component } from ‘react’;
import { StyleSheet, View, Button,Platform, Text} from ‘react-native’;
|
2. Create constructor() and inside the constructor() create a State named as TextHolder and set its default values as ‘This is Old Sample Text’ . This would be our Text component default value.
1
2
3
4
5
6
7
8
9
10
|
constructor(){
super();
this.state = {
TextHolder:‘This is Old Sample Text’
}
}
|
3. Create a function named as ChangeTextFunction() . Inside this function we would change the State value and we would call this function on button onPress.
1
2
3
4
5
6
7
8
|
ChangeTextFunction =()=> {
this.setState({
TextHolder: “This is New Text.”
})
}
|
4. Create a Root View in render’s return block and inside the Root View create a Text and Button component. Now we would set Text value using State TextHolder and call the ChangeTextFunction() function on button onPress event.
1
2
3
4
5
6
7
8
9
10
11
|
render(){
return(
<View style={styles.MainContainer}>
<Text style={{marginBottom: 20, fontSize: 20}}> {this.state.TextHolder} </Text>
<Button title=“Change Text Component Text” onPress={this.ChangeTextFunction}/>
</View>
);
}
|
5. Create Style.
1
2
3
4
5
6
7
8
9
10
11
12
|
const styles = StyleSheet.create(
{
MainContainer:
{
justifyContent: ‘center’,
alignItems: ‘center’,
flex:1,
marginTop: (Platform.OS) === ‘ios’ ? 20 : 0
}
});
|
6. Complete source code for App.js File :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
import React, { Component } from ‘react’;
import { StyleSheet, View, Button,Platform, Text} from ‘react-native’;
export default class App extends Component{
constructor(){
super();
this.state = {
TextHolder:‘This is Old Sample Text’
}
}
ChangeTextFunction =()=> {
this.setState({
TextHolder: “This is New Text.”
})
}
render(){
return(
<View style={styles.MainContainer}>
<Text style={{marginBottom: 20, fontSize: 20}}> {this.state.TextHolder} </Text>
<Button title=“Change Text Component Text” onPress={this.ChangeTextFunction}/>
</View>
);
}
}
const styles = StyleSheet.create(
{
MainContainer:
{
justifyContent: ‘center’,
alignItems: ‘center’,
flex:1,
marginTop: (Platform.OS) === ‘ios’ ? 20 : 0
}
});
|
Screenshot in Android device :