1

I have multiple select options based on the database all are displayed inside a li tag in the following format.

<ul>
    here select options are rendered in a for loop;
    <li>
       <select>
           <option value='xxx'></option>
           <option value='yyy'></option>
       </select>     
      <button
      onClick={set(selectedvalue)}
       >
          set
      </button>
    </li>
</ul>

each li will have an seperate set button how do i pass the selected value to the function.i cant use the useState since it may have many li.

Mohan Raj
  • 167
  • 12
  • 1
    You can use setState with a keyed object and update just that one property in the state. – Linda Paiste Feb 20 '21 at 03:58
  • Does this answer your question? [Retrieving value from – Abir Taheer Feb 20 '21 at 04:27
  • Are you going to have multiple ``s or will there multiple `` inside only one `select`? – codemonkey Feb 20 '21 at 05:46

2 Answers2

0

This can be achieved using useRef then getting the value from the reference to the select select. You will pass the ref into the set function and that should allow you to grab the value through current:

import React, { useRef } from "react";

const SelectExample = () => {
  const select1 = useRef(null);
  const set = (setRef) => {
    console.log(setRef.current.value);
  };

  return (
    <ul>
      here select options are rendered in a for loop;
      <li>
        <select ref={select1}>
          <option value="xxx"></option>
          <option value="yyy"></option>
        </select>
        <button onClick={set(select1)}>set</button>
      </li>
    </ul>
  );
};

export default SelectExample;
0

useRef() is certainly one way to get this done.

The first thing you want to do is create a ref to tie to your select:

const selectRef = useRef();

Then link up the select element to the ref like so:

      <ul>
        <li>
          <select ref={selectRef}>
            {ar.map((i, index) => (
              <option key={index} value={i}>
                option {i}
              </option>
            ))}
          </select>
          <button onClick={() => set(selectRef.current.value)}>set</button>
        </li>
      </ul>

As you can see, the button will grab the current value of the select and send it to your set function.

<button onClick={() => set(selectRef.current.value)}>set</button>

Here is a Sandbox for you to demonstrate the idea: https://codesandbox.io/s/dark-framework-xuhxn?file=/src/App.js

codemonkey
  • 7,325
  • 5
  • 22
  • 36