Search code examples
javascriptreactjsreact-hookssetstate

React Hooks - Select Option value and name in the same method


I have the following situation where i want to get due different values to set the State ( item.id and item.name ) when i select an item in my dropdown. At the moment i can only do for 1 value ( item.id )

How can i do in the same method, is this possible?

This is the code

  const [selectedValue, setSelectedValue] = useState("");
  const [selectedName, setSelectedName] = useState("");

  const selectValue = evt => {
    const { value } = evt.target;
    setSelectedValue(value);
  };

  <select value={selectedValue} onChange={selectValue}>
     {teamsDetail && teamsDetail.length > 0
        ? teamsDetail.map(item => (
           <option key={`${item.team_id}`} value={item.team_id}>
             {item.name}
           </option>
              ))
            : null}
   </select>

{selectedValue}
{selectedName} ??

The question is how can i now add the same logic also for te name value in in order to display for example the selectedName?

I provide the demo here => https://codesandbox.io/s/select-demo-u1o1k


Solution

  • You can get the name from teamDetail based on id

    const selectValue = evt => {
        const { value } = evt.target;
        const item = teamsDetail.find(item => item.id == value);
        setSelectedValue(value);
        setSelectedName(item.name);
      };
    

    or you could get value using nativeEvent to get option text like

     const selectValue = evt => {
        const { value } = evt.target;
        const index = evt.nativeEvent.target.selectedIndex;
        const text = evt.nativeEvent.target[index].text;
        setSelectedValue(value);
        setSelectedName(text);
      };