react select not recognizing default value

十年热恋 提交于 2021-02-16 19:56:12

问题


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.


回答1:


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")
);


来源:https://stackoverflow.com/questions/51754700/react-select-not-recognizing-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!