Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning correct value select on option – It always brings me the final result in the array

i have a problem.
I’m trying to create an option and I have a variety of options there.
Now I want when I select something from the list of options and press the Create button it will bring me the result I chose.
But for some reason it always gives me the final result in the array.

Data list

export const Form_Types = [
  { id: 1, name: "car1", url: "" },
  { id: 2, name: "car2", url: "" },
];

CreatingDocument

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import loading from "../loading.mp4";
import { Form_Types } from "../components/Form_types";
import { useRef } from "react";

function CreatingDocument() {
  const SelectRef = useRef(null);

  const handlerSubmit = (e) => {
    e.preventDefault();
    console.log(SelectRef.current.value); // **it give me alwasy car2**
  };

  return (
    <>
      <section dir="rtl" id="dashboard">
    

        <form onSubmit={handlerSubmit}>
          <label htmlFor="Form_Types">Select a vehicle type</label>

          <select name="Form_Types" id="Form_Types">
            {Form_Types.map((item) => {
              return (
                <option key={item.id} value={item.name} ref={SelectRef}>
                  {item.name}
                </option>
              );
            })}
          </select>
          <button className="btn-dark">Create</button>
        </form>
      </section>

      <video muted loop autoPlay>
        <source src={loading} type="video/mp4" />
      </video>
    </>
  );
}

export default CreatingDocument;

>Solution :

That is due to you have multiple items in Form_Types, rendering multiple option, and your selectRef is set…. on options, not on select. So selectRef is always the last rendered option, which is car2.

<select name="Form_Types" id="Form_Types" ref={SelectRef}>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading