[javascript] How to get selected value of a dropdown menu in ReactJS

I'm using react and I want to get the value of the selected option of a dropdown in react but I don't know how. Any suggestions? thanks! My dropdown is just a select like:

<select id = "dropdown">
    <option value="N/A">N/A</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

This question is related to javascript select drop-down-menu menu reactjs

The answer is


As for front-end developer many time we are dealing with the forms in which we have to handle the dropdowns and we have to use the value of selected dropdown to perform some action or the send the value on the Server, it's very simple you have to write the simple dropdown in HTML just put the one onChange method for the selection in the dropdown whenever user change the value of dropdown set that value to state so you can easily access it in AvFeaturedPlayList 1 remember you will always get the result as option value and not the dropdown text which is displayed on the screen

import React, { Component } from "react";
import { Server } from "net";

class InlineStyle extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectValue: ""
    };

    this.handleDropdownChange = this.handleDropdownChange.bind(this);
  }

  handleDropdownChange(e) {
    this.setState({ selectValue: e.target.value });
  }

  render() {
    return (
      <div>
        <div>
          <div>
            <select id="dropdown" onChange={this.handleDropdownChange}>
              <option value="N/A">N/A</option>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
            </select>
          </div>

          <div>Selected value is : {this.state.selectValue}</div>
        </div>
      </div>
    );
  }
}
export default InlineStyle;

Just use onChange event of the <select> object. Selected value is in e.target.value then.

By the way, it's a bad practice to use id="...". It's better to use ref=">.." http://facebook.github.io/react/docs/more-about-refs.html


It is as simple as that. You just need to use "value" attributes instead of "defaultValue" or you can keep both if a pre-selected feature is there.

 ....
const [currentValue, setCurrentValue] = useState(2);
<select id = "dropdown" value={currentValue} defaultValue={currentValue}>
     <option value="N/A">N/A</option>
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
  </select>
.....

setTimeut(()=> {
 setCurrentValue(4);
}, 4000);

In this case, after 4 secs the dropdown will be auto-selected with option 4.


import React from 'react';
import Select from 'react-select';

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

class App extends React.Component {
  state = {
    selectedOption: null,
  };
  handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  };
  render() {
    const { selectedOption } = this.state;

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

And you can check it out on this site.


If you want to get value from a mapped select input then you can refer to this example:

class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          fruit: "banana",
        };
    
        this.handleChange = this.handleChange.bind(this);
      }
    
      handleChange(e) {
        console.log("Fruit Selected!!");
        this.setState({ fruit: e.target.value });
      }
    
      render() {
        return (
          <div id="App">
            <div className="select-container">
              <select value={this.state.fruit} onChange={this.handleChange}>
                {options.map((option) => (
                  <option value={option.value}>{option.label}</option>
                ))}
              </select>
            </div>
          </div>
        );
      }
    }
    
    export default App;

Implement your Dropdown as

<select id = "dropdown" ref = {(input)=> this.menu = input}>
    <option value="N/A">N/A</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

Now, to obtain the selected option value of the dropdown menu just use:

let res = this.menu.value;

You can handle it all within the same function as following

_x000D_
_x000D_
<select className="form-control mb-3" onChange={(e) => this.setState({productPrice: e.target.value})}>_x000D_
_x000D_
  <option value="5">5 dollars</option>_x000D_
  <option value="10">10 dollars</option>_x000D_
                                         _x000D_
</select>
_x000D_
_x000D_
_x000D_

as you can see when the user select one option it will set a state and get the value of the selected event without furder coding require!


I was making a drop-down menu for a language selector - but I needed the dropdown menu to display the current language upon page load. I would either be getting my initial language from a URL param example.com?user_language=fr, or detecting it from the user’s browser settings. Then when the user interacted with the dropdown, the selected language would be updated and the language selector dropdown would display the currently selected language.

In the spirit of the other answers using food examples, I got all sorts of fruit goodness for you.

  • First up, answering the initially asked question with a basic React functional component - two examples with and without props, then how to import the component elsewhere.

  • Next up, the same example - but juiced up with Typescript.

  • Then a bonus finale - A language selector dropdown component using Typescript.


Basic React (16.13.1) Functional Component Example. Two examples of FruitSelectDropdown , one without props & one with accepting props fruitDetector

import React, { useState } from 'react'

export const FruitSelectDropdown = () => {
  const [currentFruit, setCurrentFruit] = useState('oranges')
  
  const changeFruit = (newFruit) => {
    setCurrentFruit(newFruit)
  }
  
  return (
    <form>
      <select 
        onChange={(event) => changeFruit(event.target.value)}
        value={currentFruit}
      >
        <option value="apples">Red Apples</option>
        <option value="oranges">Outrageous Oranges</option>
        <option value="tomatoes">Technically a Fruit Tomatoes</option>
        <option value="bananas">Bodacious Bananas</option>
      </select>
    </form>
  )
}

Or you can have FruitSelectDropdown accept props, maybe you have a function that outputs a string, you can pass it through using the fruitDetector prop

import React, { useState } from 'react'

export const FruitSelectDropdown = ({ fruitDetector }) => {
  const [currentFruit, setCurrentFruit] = useState(fruitDetector)
  
  const changeFruit = (newFruit) => {
    setCurrentFruit(newFruit)
  }
  
  return (
    <form>
      <select 
        onChange={(event) => changeFruit(event.target.value)}
        value={currentFruit}
      >
        <option value="apples">Red Apples</option>
        <option value="oranges">Outrageous Oranges</option>
        <option value="tomatoes">Technically a Fruit Tomatoes</option>
        <option value="bananas">Bodacious Bananas</option>
      </select>
    </form>
  )
}

Then import the FruitSelectDropdown elsewhere in your app

import React from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'

const App = () => {
  return (
    <div className="page-container">
      <h1 className="header">A webpage about fruit</h1>
      <div className="section-container">
        <h2>Pick your favorite fruit</h2>
        <FruitSelectDropdown fruitDetector='bananas' />

      </div>
    </div>
  )
}

export default App

FruitSelectDropdown with Typescript

import React, { FC, useState } from 'react'

type FruitProps = {
  fruitDetector: string;
}

export const FruitSelectDropdown: FC<FruitProps> = ({ fruitDetector }) => {
  const [currentFruit, setCurrentFruit] = useState(fruitDetector)
  
  const changeFruit = (newFruit: string): void => {
    setCurrentFruit(newFruit)
  }
  
  return (
    <form>
      <select 
        onChange={(event) => changeFruit(event.target.value)}
        value={currentFruit}
      >
        <option value="apples">Red Apples</option>
        <option value="oranges">Outrageous Oranges</option>
        <option value="tomatoes">Technically a Fruit Tomatoes</option>
        <option value="bananas">Bodacious Bananas</option>
      </select>
    </form>
  )
}

Then import the FruitSelectDropdown elsewhere in your app

import React, { FC } from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'

const App: FC = () => {
  return (
    <div className="page-container">
      <h1 className="header">A webpage about fruit</h1>
      <div className="section-container">
        <h2>Pick your favorite fruit</h2>
        <FruitSelectDropdown fruitDetector='bananas' />

      </div>
    </div>
  )
}

export default App

Bonus Round: Translation Dropdown with selected current value:

import React, { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'

export const LanguageSelectDropdown: FC = () => {
  const { i18n } = useTranslation()
  const i18nLanguage = i18n.language
  const [currentI18nLanguage, setCurrentI18nLanguage] = useState(i18nLanguage)
  
  const changeLanguage = (language: string): void => {
    i18n.changeLanguage(language)
    setCurrentI18nLanguage(language)
  }
  
  return (
    <form>
      <select 
        onChange={(event) => changeLanguage(event.target.value)}
        value={currentI18nLanguage}
      >
        <option value="en">English</option>
        <option value="de">Deutsch</option>
        <option value="es">Español</option>
        <option value="fr">Français</option>
      </select>
    </form>
  )
}

An invaluable resource for React/Typescript


Using React Functional Components:

const [option,setOption] = useState()

function handleChange(event){
    setOption(event.target.value)
}

<select name='option' onChange={handleChange}>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to select

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option> SQL query to check if a name begins and ends with a vowel Angular2 *ngFor in select list, set active based on string from object SQL: Two select statements in one query How to get selected value of a dropdown menu in ReactJS DATEDIFF function in Oracle How to filter an array of objects based on values in an inner array with jq? Select unique values with 'select' function in 'dplyr' library how to set select element as readonly ('disabled' doesnt pass select value on server) Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working How to implement drop down list in flutter? How can I create a dropdown menu from a List in Tkinter? How can I close a dropdown on click outside? Making a drop down list using swift? HTML: Select multiple as dropdown How to get selected value of a dropdown menu in ReactJS Avoid dropdown menu close on click inside Bootstrap 3 dropdown select How to make a drop down list in yii2? Android custom dropdown/popup menu What is the hamburger menu icon called and the three vertical dots icon called? Changing text color of menu item in navigation drawer How to get selected value of a dropdown menu in ReactJS Android custom dropdown/popup menu Creating a Menu in Python How to make a 3-level collapsing menu in Bootstrap? how to set active class to nav menu from twitter bootstrap How to make jQuery UI nav menu horizontal? Twitter Bootstrap add active class to li Adding a right click menu to an item

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release