user4747724
user4747724

Reputation:

react select not recognizing default value

I have a react select component that isn't recognizing the default value option. The code looks like this:

renderPlans(){
        if(this.props.plans){
            let list =  this.props.plans.map(item=>{
                return ({label:item.description, value:item.id})
            });

            return(
                <Select
                    name= "tile-plans"
                    value= {this.state.selected}
                    classNamePrefix='react-select-container'
                    options={list}
                    defaultValue={list[0]}
                    onChange={(e) => { e ? this.setState({selected: e.value}) : this.setState({selected: ''}) }}
                />
            )
        }
    }

from everything I can find on its docs this is the format to give it. Basically I just want the first option to always be the default choice as there will be times when there is only 1 option and it doesn't make sense for someone to need to select a drop down. I also have a graph that's being loaded underneath so if an option is selected the graph won't load.

This isn't a duplicate question as I know you can do it like this: value= {this.state.selected ? this.state.selected:list[0].label} but it's not working. The input remains blank on load.

Upvotes: 4

Views: 7539

Answers (1)

Tholle
Tholle

Reputation: 112777

The documentation states that "If you don't provide these props, you can set the initial value of the state they control", referencing among others the value prop you provide.

You can set the selected to the first element in list when the component is created instead.

Example

class App extends React.Component {
  state = {
    selected: this.props.list[0]
  };

  handleChange = selected => {
    this.setState({ selected });
  };

  render() {
    const { selected } = this.state;

    return (
      <Select
        value={selected}
        onChange={this.handleChange}
        options={this.props.list}
      />
    );
  }
}

ReactDOM.render(
  <App
    list={[
      { value: "chocolate", label: "Chocolate" },
      { value: "strawberry", label: "Strawberry" },
      { value: "vanilla", label: "Vanilla" }
    ]}
  />,
  document.getElementById("root")
);

Upvotes: 1

Related Questions