Search code examples
reactjsonclickonchangereact-select

How to use selectedOption in react-select


I use react-select and I'm new.I have a component called Example that executes the handleChange method correctly

const colourOptions = [
  { value: '1', label: '1', color: '#00B8D9' },
  { value: '2', label: '2', color: '#0052CC' },
  { value: '3', label: '3', color: '#5243AA' },
];

class Example extends React.Component {
  state = {
    selectedOption: null,
  }

  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(selectedOption)
  }

  render() {
    const { selectedOption } = this.state;
    return (
        <Select
          value={selectedOption}
          onChange={this.handleChange}
          options={colourOptions}
        />
    );
  }
}

export default Example;

In another file we have a button

export default function UserProfile() {
  return (
    <div>

      <Example1/>
      <Example2/>
      <Example3/>

      <Button type="Submit">Search</Button>

    </div>
  );
}

How can I display the value of selectedOption by clicking on the button?


Solution

  • The correct way is to maintain the selectedOption and the handleChange in the parent(UserProfile) and pass them down to the child(Example).

    UserProfile Component

    export default function UserProfile() {
      const [selectedOption, setSelectedOption] = useState({});
    
      const handleChange = (selectedOption) => {
        setSelectedOption(selectedOption)
        console.log(selectedOption)
      };
    
      const handleClick = () => {
        console.log(selectedOption);      
      };
    
      return (
        <div>
    
          <Example onHandleChange={handleChange} selectedOption={selectedOption}/>
    
          <Button onClick={handleClick} type="Submit">Search</Button>
    
        </div>
      );
    }
    

    Example Component

    class Example extends React.Component {
    
      render() {
        const { selectedOption, onHandleChange } = this.props;
    
        return (
            <Select
              value={selectedOption}
              onChange={onHandleChange}
              options={colourOptions}
            />
        );
      }
    }
    
    export default Example;