Input type text value not updating when using React JS

I am using React JS to display input type = "text". I know that if you use a property value

, React renders the readonly textbox. So, I wrote a small part of mine (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 display this component with a different value, I don't see the component update with the updated value.

+3


source to share


1 answer


Every time I try to display this component with a different value, I don't see the component update with the updated value.

You mean you work

<MyComponent value={someValue} />

      

with different meanings?

Unless in this case the component does not use the new value, because you are not talking about it.



The component maintains its state between repeaters, and the value displayed in the text box comes from state. If you don't update the state based on the new props, nothing will change. You must implement componentWillReceiveProps

:

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

      

From the docs:

Called when a component receives new props. This method is not called for the original render.

Use this as an opportunity to react to the prop transition before being render()

called by updating the state with this.setState()

. Old details can be accessed through this.props

. Calling this.setState()

inside this function will not trigger additional rendering.

Learn more about lifecycle methods.

+7


source







All Articles