Search code examples
javascriptreactjsreact-selectrequired

How to add required to react-select?


I'm using react-select library to add dropdown menu for my app, but "required" doesn't work (I read a discussion on GitHub for this library, creators haven't added that function yet), so for now how do I make select required? (I read here another post with the same problem, solution presented there didn't work for me). My code is:

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

export default function App() {
  const [data, setData] = useState();
  const options = [
    { value: "1", label: "1" },
    { value: "2", label: "2" },
    { value: "3", label: "3" },
    { value: "4", label: "4" }
  ];

  const handleSubmit = (e) => {
    console.log(data);
  };
  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <input required placeholder="name" />
        <Select
          options={options}
          onChange={(e) => setData(e.value)}
          value={options.filter(function (option) {
            return option.value === data;
          })}
          label="Single select"
          placeholder={"Select "}
          menuPlacement="top"
          required
        />

        <button> Submit</button>
      </form>
    </div>
  );
}

code sandbox

In my code I have a couple of regular inputs (where required works fine) but I want the Select also be required. Any suggestions are greatly appreciated.


Solution

  • I would think outside the box — in this case the Select component. What can you add that gets the same result? I took a quick stab at this for you:

    const [isValid, setIsValid] = useState(false);
    
    // This effect runs when 'data' changes
    useEffect(() => {
      // If there is data, the form is valid
      setIsValid(data ? true : false);
    }, [data]);
    
    ...
    
    return (
      <div>
        <Select ... />
        {!isValid && <p>You must choose a value</p>}
        <button disabled={!isValid}>Submit</button>
      </div>
    )
    

    https://codesandbox.io/s/vigilant-wiles-6lx5f

    In this example, we check the state of the Select component — if it's empty (the user hasn't chosen anything) the form is invalid and the submit button is disabled.