Home > Back-end >  React adding custom props to vanilla html elements
React adding custom props to vanilla html elements

Time:03-20

      const handleChange = (e) => {
          console.log(e.target.id);
    };

    return (
      <div>
        <select onChange={(e) => handleChange(e)}>
          <option value="1-10" id="foo">
            1-10
          </option>

How can I make the id prop in the <option> tag accessible by the code above? e.target.id returns nothing, but e.target.value returns the selected value. How can I create these custom attributes with when using vanilla html elements?

CodePudding user response:

e.target is the select, not the option. And since the select does not have an id, you are getting nothing. One way to achieve what you want is by doing so :

export default function App() {
  const handleChange = (e) => {
    const selectedOption = e.target.querySelector(`option[value='${e.target.value}']`);
    console.log(selectedOption.id);
  };
  return (
    <select onChange={(e) => handleChange(e)}>
      <option value="1-10" id="foo">
        1-10
      </option>
      <option value="1-11" id="bar">
        1-11
      </option>
    </select>
  );
}

CodePudding user response:

One of the easiest method to achieve this is as follows:

const handleChange = (e) => {
    const index = e.target.selectedIndex;
    const id = e.target.childNodes[index].id;
    console.log(id); // logs 'foo' or 'bar' depending on selection
  };

  return (
    <div>
      <select onChange={(e) => handleChange(e)}>
        <option value="1-10" id="foo">
          1-10
        </option>
        <option value="11-20" id="bar">
          11-20
        </option>
      </select>
    </div>
  );

CodePudding user response:

Here's another way to do so

import React from 'react';

const handleChange = (e) => {
  const index = e.target.selectedIndex;
  const el = e.target.childNodes[index]
  const option =  el.getAttribute('id'); 
  console.log(option)
};

export function App(props) {
  return (
    <div className='App'>
      <select onChange={(e) => handleChange(e)}>
        <option value="1-10" id="foo">
          1-10
        </option>
        <option value="2-10" id="zoo">
          2-10
        </option>
      </select>
    </div>
  );
}
  • Related