I got the following Component and I want to init TextInput with defaultValue and then when user type update the value of it.
How do I do that?
Here what I've tried - but this way TextInput is always empty on initialization.
class Note extends Component {
state = {
text: ""
};
render() {
const {onChange} = this.props;
return (
<TextInput
onChangeText={(text) => {
this.setState({text});
onChange(text);
}
value={this.state.text}
defaultValue={this.props.text}
/>
);
} }
"react": "^16.4.1"
"react-native": "^0.55.4",
Finally solved it,
The key is the following - "value" has preceding over "defaultValue" unless "value" is undefined!
So, Init this.state.text = undefined
, this way defaultValue can be initialized with this.props.text.
class Note extends Component {
state = {
text: undefined
};
render() {
const {onChange} = this.props;
return (
<View>
<TextInput
onChangeText={(text) => {
this.setState({text});
onChange(text);
}
value={this.state.text}
defaultValue={this.props.text}
/>
</View>
);
}
}
I found this a bit more clean than @anilSidhu solution.
You can set default value in state
itself like following:
class Note extends Component {
state = {
text: this.props.text
};
render() {
const {onChange} = this.props;
return (
<TextInput
onChangeText={(text) => {
this.setState({text});
onChange(text);
}
value={this.state.text}
/>
);
} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With