Home > OS >  Access selected value from react's Select Component
Access selected value from react's Select Component

Time:01-02

Hello dear community,

I want to create a very basic website for my school assignment. I have a dropdown menu with a Select Component as its implementation. I need to access the selected value, which is a currency in my case, in order to update the information displayed on the page once a currency has been selected.

I am kind of frustrated since I wasn't able to find a helpfull solution to my relatively basic problem (I think it's basic :D)

My component class here:

import { Component } from "react";
import Select from 'react-select';


interface DropdownMenuProps {
  values: [{}]
  defaultValue: string
}

interface DropdownMenuState { }

/**
 * Represents a Dropdown Menu
 */
export default class DropdownMenu extends Component<DropdownMenuProps, DropdownMenuState> {

  render() {
    return (
      <div style={{ width: '120px' }}>
        <Select id="dropdown-menu"
          placeholder={this.props.defaultValue}
          options={this.props.values}
        // getOptionValue={(option) => option.value}
        // getOptionLabel={(option) => option.label}
        />
      </div>
    )
  }
}

This is how I create a dropdown menu compent:

<DropdownMenu defaultValue="Currency" values={[{ label: "EUR", value: "EUR" }, { label: "GBP", value: "GBP" }, { label: "USD", value: "USD" }]} ></DropdownMenu>

I'm glad for any tips :)

CodePudding user response:

You have to use the onChange prop of react-select:

<select
id="dropdown-menu"
onChange={handleSelectChange}
>

and in this function you could handle the changes:

const handleSelectChange = (selectedVal) => console.log(selectedVal)

CodePudding user response:

I recommend you using directly onChange and save it into a state:

1st: Create state with the name you want:

const [selectValue, setSelectValue] = useState({});

2nd: Create options:

  const options = [
    { label: "Tomate", value: 1 },
    { label: "Queso", value: 2 }
  ];

3rd: add method onChange in select and pass options:

  const onChange = (ev) => {
    setSelectValue(ev);
    //console.log(ev);
    console.log(selectValue);
  };

  <Select
    id="dropdown-menu"
    placeholder={"e"}
    options={options}
    onChange={onChange}
  />

I have created demo here:

https://codesandbox.io/s/ancient-pond-96h53?file=/src/App.js

  • Related