Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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",

like image 647
chenop Avatar asked Aug 10 '18 07:08

chenop


2 Answers

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.

like image 162
chenop Avatar answered Nov 15 '22 09:11

chenop


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}
                />
        );
    } }
like image 38
Riddhi Avatar answered Nov 15 '22 11:11

Riddhi