Reputation: 5143
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",
Upvotes: 11
Views: 26434
Reputation: 39
For someone having trouble with this problem. I've experienced it. i expect my number Value
to be displayed on Textinput
. But placeholders keep showing.
The solution is your Value
must be String.
So i convert my Number
to String
use toString()
method.
Hope this helps.
Upvotes: 3
Reputation: 11
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)}
Upvotes: 1
Reputation: 31
Basically, when you're having both value
and defaultValue
props, always value
prop will take precedence and thus defaultValue
won't be reflected.
Upvotes: 2
Reputation: 5143
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.
Upvotes: 23
Reputation: 963
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
Upvotes: 3
Reputation: 777
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}
/>
);
} }
Upvotes: 3