How to get selected value in React Select?

React Select is a popular library used by developers to create custom dropdown menus in React applications. One common requirement when working with React Select is to retrieve the selected value from the dropdown. In this article, we will explore different approaches to get the selected value in React Select and discuss some related FAQs.

How to get selected value in React Select?

The React Select library provides a few ways to obtain the selected value. Here are three common approaches:

1. Using onChange event handler

One way to get the selected value in React Select is by utilizing the onChange event handler. This event is triggered whenever a new option is selected. By storing the selected value in the component’s state, we can easily retrieve it. Here’s an example:

“`jsx
import React, { useState } from ‘react’;
import Select from ‘react-select’;

const MySelect = () => {
const [selectedValue, setSelectedValue] = useState(null);

const handleChange = (option) => {
setSelectedValue(option); // Store the selected value in state
};

return (

);
};
“`

In this example, the ref `selectRef` is assigned to the React Select component. When the button is clicked, the selected value can be accessed using `selectRef.current.state.value`.

3. Accessing the selected value directly

The React Select library also provides a property called `defaultValue` that can be used to set the initial selected value. By passing the selected value as `defaultValue`, we can access it directly whenever needed.

“`jsx
import React from ‘react’;
import Select from ‘react-select’;

const MySelect = () => {
const selectedValue = defaultValue; // Replace defaultValue with the value obtained from your data source

const handleButtonClick = () => {
console.log(selectedValue);
};

return (