Search code examples
reactjsdropdownonchange

Setting value in a react-dropdown Dropdown's onChange callback throws an error


I am using Dropdown from react-dropdown to display some options. Every time a user clicks on a option from list, the value of option should change. As per my code, it changes for the first time. However after choosing second time from list, it gives TypeError saying options.map is not a function. How can I fix this?

import React, { useState, useEffect } from "react";
import Dropdown from "react-dropdown";
import "react-dropdown/style.css";
import "./styles.css";

function App() {
  const [options, setOptions] = useState(["one", "two", "three"]);
  const defaultOption = options[""];
  
  useEffect(() => {
    console.log(options.value);
  }, [options.value]);

  return (
    <div className="App">
      <Dropdown
        options={options}
        onChange={(value) => setOptions(value)}
        value={defaultOption}
        placeholder="Select an option"
      />
    </div>
  );
}
export default App;

Solution

  • The problem is that you are changing the array of options as the user select an option in drop down

    You must concern if options must be a state or just the selected value

    I've rewrote for you as I imagine is the right way to do it

    import React, { useState, useEffect } from "react";
    import Dropdown from "react-dropdown";
    import "react-dropdown/style.css";
    import "./styles.css";
    
    function App() {
      const [selectedOption, setSelectedOption] = useState("");
      const options = ["one", "two", "three"];
    
      useEffect(() => {
        console.log(selectedOption);
      }, [selectedOption]);
    
      return (
        <div className="App">
          <Dropdown
            options={options}
            onChange={({ value }) => setSelectedOption(value)}
            value={selectedOption}
            placeholder="Select an option"
          />
        </div>
      );
    }
    export default App;