Home > Enterprise >  How to generate buttons below the dropdown with onSelect on react js?
How to generate buttons below the dropdown with onSelect on react js?

Time:11-24

So when i choose the first option, 5 buttons should appear below dropdown, second option should have 9 buttons (it's different for every option), should i create json for buttons? i'm lost on how to do it, please help me out

CodePudding user response:

You want to store the state of the selected item in the select element.

Then using this value you want to "conditionally render" different buttons.

Check out this codesandbox.

import { useState } from "react";

export default function App() {
  const [selected, setSelected] = useState("op1");

  const selectionChanged = (e) => setSelected(e.target.value);

  return (
    <div className="App">
      {/* SELECT COMPONENT */}
      <select value={selected} onChange={selectionChanged}>
        <option value="op1">Option 1</option>
        <option value="op2">Option 2</option>
      </select>

      {/* IF OPTION 1 IS SELECTED */}
      {selected === "op1" && (
        <>
          <button>Button 1</button>
          <button>Button 2</button>
        </>
      )}

      {/* IF OPTION 2 IS SELECTED */}
      {selected === "op2" && (
        <>
          <button>Button 3</button>
          <button>Button 4</button>
          <button>Button 5</button>
        </>
      )}
    </div>
  );
}
  • Related