Home > Software engineering >  Storing react-select component value
Storing react-select component value

Time:12-16

I am using the react-select component instead of the <select> HTML tag.

I want to store the selected value and handle the change (onChange) function.

I tried a standard way, setting a useState hook and assigning the value to the <Select> component with the onChange function handler, but it is not working.

How can I achieve what I need?

Here is the component snippet showing what I tried to do :

import React, { useState } from "react";
import Select from "react-select";

const Options = () => {
    const options = [
        { value: "chocolate", label: "Chocolate" },
        { value: "strawberry", label: "Strawberry" },
        { value: "vanilla", label: "Vanilla" },
    ];

    const [selectedValue, setSelectedValue] = useState(options[0])
    const selectHandler = (e) => {
        setSelectedValue(e.target)
    }
    console.log(selectedValue)
    return <Select options={options} value={selectedValue} onChange={selectHandler} />;
};

export default Options;

CodePudding user response:

When handling the onChange of a select, it is slightly different to a regular input. The value that gets passed is one of the options that were given to the select element. So no target.value

You could implement it as follows :

  const [value, setValue] = React.useState({
    value: "Select",
    label: "Select"
  });

  const options = [
    // Default Value
    { value: "Select", label: "Select" },
    { value: "chocolate", label: "Chocolate" },
    { value: "strawberry", label: "Strawberry" },
    { value: "vanilla", label: "Vanilla" }
  ];
  const handleChange = (val) => {
    setValue(val);
  };

  return (
    <>
      <Select options={options} value={value} onChange={handleChange} />
      <p>You selected : {value.label}</p>
    </>
  );

CodeSandBox Example : https://codesandbox.io/s/small-sky-gjikbr?file=/src/App.js:117-641

In the following example, I created a default value. This is something I recommend so that you can implement validation. if value === select then show error.

Side tip: If I were to implement a select. I would create a constant like this :

const optionsConstant = {
  Select: 0,
  chocolate: 1,
  strawberry: 2,
  vanilla: 3
}

Then Change the options to reflect it

 const options = [
   // Default Value
   {
     value: 0,
     label: "Select"
   },
   {
     value: 1,
     label: "Chocolate"
   },
   {
     value: 2,
     label: "Strawberry"
   },
   {
     value: 3,
     label: "Vanilla"
   }
 ];

Finally I would store the value as a number and do checks in like this

if(value === optionsConstant.Select) ShowError

  • Related