I’ve got a react native form with a button that should autofill some of the field based on some user’s information. The point is that even if I update the state variable related to a TextInput, the TextInput does not display such data. Here’s a short snippet for the sake of simplicity
JavaScript
x
32
32
1
export default class Component extends React.Component {
2
constructor(props) {
3
super(props);
4
5
this.state = {
6
value: null
7
}
8
}
9
10
autocompile = () => {
11
this.setState({"value": "new value"})
12
}
13
14
render() {
15
return (
16
<View>
17
<TouchableOpacity
18
onPress={() => {
19
this.autocompile
20
}}>
21
<Text>Autocompile</Text>
22
</TouchableOpacity>
23
<TextInput
24
onChangeText={(value) => this.setState({'value': value})}
25
value={this.state.value}
26
/>
27
</View>
28
)
29
}
30
}
31
}
32
Following this example, if I clicked “Autocompile”, the TextInput below wouldn’t show the new value, even though the state variable would be updated. My question is, how can I update a TextInput displayed value from the external without typing in?
Advertisement
Answer
Class Component Solution
JavaScript
1
29
29
1
import React from 'react';
2
import { Text, View, TextInput, TouchableOpacity } from 'react-native';
3
4
export default class Component extends React.Component {
5
constructor(props) {
6
super(props);
7
this.state = { value: '' };
8
this.autocompile = this.autocompile.bind(this);
9
}
10
11
autocompile() {
12
this.setState({ value: 'new value' });
13
}
14
15
render() {
16
return (
17
<View>
18
<TouchableOpacity onPress={this.autocompile}>
19
<Text>Autocompile</Text>
20
</TouchableOpacity>
21
<TextInput
22
onChangeText={(value) => this.setState({ value: value })}
23
value={this.state.value}
24
/>
25
</View>
26
);
27
}
28
}
29
Function Component Solution
JavaScript
1
20
20
1
import React, { useState } from 'react';
2
import { View, TouchableOpacity, Text, TextInput } from 'react-native';
3
4
const App = () => {
5
const [value, setValue] = useState('');
6
7
const autocompile = () => setValue('new value');
8
9
return (
10
<View>
11
<TouchableOpacity onPress={() => autocompile()}>
12
<Text>Autocompile</Text>
13
</TouchableOpacity>
14
<TextInput onChangeText={(value) => setValue(value)} value={value} />
15
</View>
16
);
17
};
18
19
export default App;
20