Home > database >  please how can i log out ....key?... when the select event takes place?
please how can i log out ....key?... when the select event takes place?

Time:12-13

please how can i log out ....key?... when the select event takes place???? that is .. the key ={localState.id} inside the html <select></select>?

i need the key value to be use in a conditional statement

export default function unitFunc(){
  const lenghtArray = [
    { id: 1, value: "meter" },
    { id: 2, value: "kilometer" },
    { id: 3, value: "centimetre" },
    { id: 4, value: "milimetre" },
    { id: 5, value: "mile" },
    { id: 6, value: "yard" },
    ];


  const selectConversion = (event) => {
    const key = event.target.key;
    console.log(key);
  };

  return (
    <select>
      {lenghtArray.map((localState) => (
        <option key={localState.id}> {localState.value}</option>
      ))}
    </select>
  )
}

CodePudding user response:

const selectConversion = (event) => {
   const key = event.target.key;
    console.log(key);
  };

 <select onChange={selectConversion}>
    {lenghtArray.map((localState) => (
      <option key={localState.id} value={localState.value}>
       
        {localState.value}
      </option>
    ))}
  </select>

You can listen to option change event with onChange on <select></select> tag and trigger your function to implement logout

CodePudding user response:

You want to add the selectConversion function to the onChange prop for a select tag, like so:

const Example = () => {
  const lenghtArray = [{
      id: 1,
      value: "meter"
    },
    {
      id: 2,
      value: "kilometer"
    },
    {
      id: 3,
      value: "centimetre"
    },
    {
      id: 4,
      value: "milimetre"
    },
    {
      id: 5,
      value: "mile"
    },
    {
      id: 6,
      value: "yard"
    },
  ];

  const selectConversion = (event) => {
    const newValue = event.target.value;
    console.log(newValue);
  };

  return (
    <select onChange={selectConversion}>
    {
      lenghtArray.map((localState) => (
      <option
        key={localState.id}
        value={localState.value}
      >
        {localState.value}
      </option>
      ))
    }
    </select>)
};

// Render it
ReactDOM.createRoot(
  document.getElementById("root")
).render( <
  Example / >
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

But you will then want to target event.target.value inside selectConversion

  • Related