Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-select component value not updating.

Just wondering what I am doing wrong here. When I select a value out of the list the component input field is not being filled in with the value.

class Search extends Component {
constructor(props) {
    super(props);
    this.state = {
        name: 'order_select_field',
        placeholder: "Make a selection",
    }
}

componentWillMount () {
    fetch('http://apirequest.com')
        .then( function(response) {
            return response.json();
        })
        .then(function(json) {
            this.setState({options: json});
        }.bind(this))
    }

handleChange(event) {
    this.setState({ })
}

render() {
    return (
        <div>
            <Select
                name={this.state.name}
                options={this.state.options}
                placeholder={this.state.placeholder}
            />
        </div>
    )
}

}

like image 695
Jasonca1 Avatar asked Aug 29 '17 21:08

Jasonca1


1 Answers

Your main issue is your handleChange method doesn't set the value

handleChange = (event) => {
  this.setState({
    ...this.state,
    value: event.target.value
  })
}

With a vanilla <select> component, the onChange event would have a DOMElement reference at event.target, and react provides the value prop on the DOM element do you can use it to update your state. You're 3rd-party <Select> component might have a different event signature or expectation.

Also, since I don't know what library you're using, I've provided the state key which tracks your value as "yourSelectKey", but you can replace this with the correct key. If it's a nested property (part of an object), you may have to add the spread operator so that the other values get copied over as well.

And you need to add the onChange event handler to your select component. I recommend you follow the react docs instead of using that library.

<select
  value={this.state.value}
  onChange={this.handleChange}>
  name={this.state.name}>

    <option value="value1">Value 1</option>
    <option value="value2">Value 2</option>
    <option value="value3">Value 3</option>

</select>

Other issues you're facing:

  • You need to bind handleChange to your object instance. You can either do this in the constructor with a line this.handleChange = this.handleChange.bind(this) or by declaring handleChange as an instance variable, as I have done above.
  • as the commenter said, you should avoid doing the fetch call in componentWillMount, but should use componentDidMount. This is a common mistake for beginners.
like image 144
Julian Soro Avatar answered Sep 28 '22 18:09

Julian Soro