3

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.

0

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.