简体   繁体   中英

Can we use a value for defaultValue in react-select that is passed from another component as props?

The passed prop has same values as the one in the options array. The reason why I am doing it this way is because I am using a modal to edit a row. The data is passed from row to modal. Modal has the options but I want the data to be pre-populated. There seems no way that I can populate the react-select dropdown. `options = [ { id: 0, value: 'New', label: 'New' }, { id: 1, value: 'In Progress', label: 'In Progress' }, { id: 2, value: 'Blocked', label: 'Blocked' }, { id: 3, value: 'Complete', label: 'Complete' } ];

getSelectedStatus = (status) => {
    this.options.map((selected) => {
        if (selected.value === status) {
            this.setState({
                selectedOption: selected.id
            });
        }
    });
    console.log(this.state.selectedOption);
};`

I used a function like this to get the selectedOption id and then at least that way pass to the defaultValue property inside render(), but it is not working. Any help please?

You need to trigger the selected option on every onChange event. If you use it as in the example I shared below, you can use this component by calling all its fields and sending the data in options.

 static defaultProps = {
    options: [],
    components: undefined,
  };

handleChange = (selectedOption) => {
    const { onChange } = this.props;
    onChange(selectedOption.value);
  };



 render() {
    const {
      value, name, options, components} = this.props;
    return (
      <Select
        name={name}
        value={(value === '') ? null : options.find(obj => obj.value === 
        value)}
        onChange={this.handleChange}
        options={options}
        className="react-select"
        classNamePrefix="react-select"
        
      />
    );
  }




  return (
    <>
      <SelectField
        {...input}
        options={options}
        components={components}
      />
   
  );
};

renderSelectField.defaultProps = {
  options: [],
  components: undefined,
};

You can send the data in the field you want to use as follows.

  options={data && data.map((values) => { return ({value: values?.id, label: values?.label}); })}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM