DEV Community

Cover image for Simple React Dropdown List Component
Diego Lorenesi
Diego Lorenesi

Posted on

Simple React Dropdown List Component

So here's something I had a tough time googling. I needed to create a dropdown list that makes the component re-render once selected using react hooks. Although it's incredibly simple, I was stumped for quite some time. Here's the code:

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [selectedValue, setSelectedValue] = useState(0);
  const items = [
    { label: "Default", value: selectedValue },
    { label: "2 Rows", value: 2 },
    { label: "4 Rows", value: 4 },
    { label: "6 Rows", value: 6 }
  ];

  const handleChange = (event) => {
    console.log(event.target.value);
    setSelectedValue(event.target.value);
  };

  return (
    <div className="App">
      <h1>Simple Dropdown List</h1>
      <form>
        <select className="form-select" onChange={handleChange}>
          {items.map((item) => (
            <option key={item.label} value={item.value}>
              {item.label}
            </option>
          ))}
        </select>
      </form>
      <p>You have selected: {selectedValue}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Hope this helps!

Top comments (0)