nextjs14nextui

I am using the Select from next ui but can figure out how to get the selected value out of it ans save it in a state


I am using the Select from the next ui in my nextjs project i have succesfully implemented it and it is working fine but the problem is i cant get the selected value from it, i want to store the selected value inside a setState and i have tried using the onchange as the documentation suggested but i am getting the index instead of the string itself

Here's my code


   "use client";
   import React, { useState } from "react";
   import { Select, SelectItem } from "@nextui-org/select";

   const ServiceInfoContainer = () => {
   const [service, setService] = useState("");

   const categories = ["Beginner (0-1 year)", "Intermediate (2-3 years)", "Experienced (4-5        years)", "Expert (6+ years)"];

  const handleChange = (e)=> setService(e.target.value)

   <Select  onChange={handleChange} label="Select years of experience">
            {categories.map((categ, index) => (
              <SelectItem  key={index} value={categ}>
                {categ}
              </SelectItem>
            ))}
          </Select>
   }

when i console log the service i am getting 1 2 3 respective to the selected option like its giving me out the index instead of the string value

I want to get the selected value instead of the index i am currently getting


Solution

  • Your problem is the key, just use the intended value as the key in this example the category is the value so use it as the key.

    "use client";
    
    import React, { useState } from "react";
    import { Select, SelectSection, SelectItem } from "@nextui-org/select";
    const ServiceInfoContainer: React.FC = () => {
      const [service, setService] = useState<string>("");
    
      const categories: string[] = [
        "Beginner (0-1 year)",
        "Intermediate (2-3 years)",
        "Experienced (4-5 years)",
        "Expert (6+ years)",
      ];
    
      const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        setService(e.target.value);
      };
    
      return (
        <>
          Service: {service}
          <Select onChange={handleChange} label="Select years of experience">
            {categories.map((categ) => (
              <SelectItem key={categ} value={categ}>
                {categ}
              </SelectItem>
            ))}
          </Select>
        </>
      );
    };
    
    export default ServiceInfoContainer;

    enter image description here