How can I change the input field in a reaction?

advertisements

I want to create a normal input field, that allows typing by the user, as well as being "autocompleted" with some data from it's parent.

class SimpleForm extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            form_name: "",
            price: ""
        }
    }

    render()
    {
        return (
            <form>
                <div className="form-group">
                    <input value={this.state.form_name} onChange={(e) => { this.setState({form_name: e.target.value}) }}/>
                </div>
            </form>
        );
    }
}

class ParentOfForm extends React.Component
{
    render()
    {
        return (
            <SimpleForm howDoIsendToInputField="garbage" />

        )

    }

}

If I use defaultValue in the input field, I can't change it later on. If I set <input value={this.props.something}>, I can't modify the input field...


Your initializing ParentOfForm with prop howDoIsendToInputField = garbage. So you might rewrite your constructor of SimpleForm to use the prop from the parent form as initial state value:

constructor(props) {
  super(props);

  this.state = {
    form_name: props.howDoIsendToInputField,
  };
}

That way you have pre-filled the input field with your prop value. In the React lingo your input field is controlled now, since you provide a specific value.

The react docs just added a new section that illustrates this: https://facebook.github.io/react/docs/forms.html#handling-multiple-inputs

What you can do to reflect changes in the prop is to use componentWillReceiveProps within your SimpleForm component:

componentWillReceiveProps(nextProps) {
  this.setState({ form_name: nextProps.howDoIsendToInputField });
}

Docs: https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops