'React Native - TextInput - How to use value & defaultValue together
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",
Solution 1:[1]
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}
/>
);
} }
Solution 2:[2]
class Note extends Component {
state = {
text: undefined
};
componentDidMount() {
this.setState({ text: this.props.text })
}
render() {
return (
<TextInput
onChange={(text) => {
this.setState({ text: text.target.value });
}}
value={this.state.text}
/>
);
}
}
It should work for you and if you are still facing the issue let me know please
Solution 3:[3]
Basically, when you're having both value and defaultValue props, always value prop will take precedence and thus defaultValue won't be reflected.
Solution 4:[4]
Sometimes if you are showing number type to default value it doesn't work. you must convert to string type as follows:
defaultValue(String(this.props.text)}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Riddhi |
| Solution 2 | anil sidhu |
| Solution 3 | lubegasimon |
| Solution 4 | Vincent Doba |
