Home > OS >  Resetting a react-select field to the first value of array with button click
Resetting a react-select field to the first value of array with button click

Time:11-02

I want to create a select input where the value is always reset to the first value of the options array

import Select from 'react-select';
import {useState} from 'react';
function Component(){

  const options = [{value: "something", label: "Something"}, ...]
  const [inputValue, setInputValue] = useState("");
  const [inputValue2, setInputValue2] = useState("");
  

  return (
    <div>
      <Select 
        options={options}
        onChange={(e) => setInputValue(e.value)}
        value={inputValue}
      />
      <Select 
        options={options}
        onChange={(e) => setInputValue2(e.value)}
        value={inputValue2}
      />
      <button onClick={handleReset}>Clear all Values</button>
    </div>
  )
}

When the button is clicked, all values of the select fields should be reset to the first value of the options array, how can I achieve this?

This is really important to me.

CodePudding user response:

You can set it that if nothing it selected then the first value of the array will be selected.

value={inputValue || options[0]}

The handleReset function essentially resets the values to the empty string in which case the select field will fall back onto the first value of the array.

Note: this will also set the select field to the first value when the page loads before a selection has been made.

Remember that when using the react-select package, when setting the value, the component expects both the value and the label (i.e. {value: "1", label: "one"})

import Select from 'react-select';
import {useState} from 'react';
function Component(){

    const options = [{value: "1", label: "one"}, {value: "2", label: "two"}]
    const [inputValue, setInputValue] = useState("");
    const [inputValue2, setInputValue2] = useState("");
    
    const handleReset = () => {
       setInputValue(options[0]);
       setInputValue2(options[0]);
    }

    return (
        <div>
        <Select 
        options={options}
        onChange={(e) => setInputValue(e)}
        value={inputValue || options[0]}
        />
        <Select 
        options={options}
        onChange={(e) => setInputValue2(e)}
        value={inputValue2 || options[0]}
        />
        <button onClick={handleReset}>Clear all Values</button>
    </div>
    )
}
  • Related