Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input type text's value not getting updated while using React JS

I am using React JS to render an input type="text". I know that if you use the value property React renders a readonly textbox. So, I wrote a small component of my own(see below).

React.createClass({
    getInitialState: function() {
        var self = this;
        return {value: self.renderDefault(self.props.value, '')};
    },
    handleOnChange: function(event) {
        this.setState({value: event.target.value});

        if (this.props.onChange){
            this.props.onChange(event);
        }
    },
    renderDefault : function(value, defaultValue){
        return typeof value !== 'undefined' ? value : defaultValue; 
    },
    render: function() {
        var value = this.state.value;

        return (<input type="text"
                      size={this.renderDefault(this.props.size, 1)}
                     value={value}
                  onChange={this.handleOnChange}
               placeholder={this.renderDefault(this.props.placeholder, '')}
                    />);
    }
});

Every time I try to render this component with a different value I don't see the component getting updated with the updated value.

like image 784
mohkhan Avatar asked Jun 23 '26 18:06

mohkhan


1 Answers

Everytime I try to render this component with a different value I don't see the component getting updated with the updated value.

You mean you are running

<MyComponent value={someValue} />

with different values?

If that's the case, the component does not use the new value because you are not telling it to.

The component keeps its state between rerenders and the value shown in the text field comes from the state. If you don't update the state based on the new props, nothing will change. You have to implement componentWillReceiveProps:

componentWillReceiveProps: function(nextProps) {
    this.setState({value: nextProps.value});
}

From the docs:

Invoked when a component is receiving new props. This method is not called for the initial render.

Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.

More about lifecycle methods.

like image 86
Felix Kling Avatar answered Jun 25 '26 08:06

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!