Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

75
Views
React adding custom props to vanilla html elements
      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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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>
  );
about 4 years ago · Juan Pablo Isaza Report

0

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>
  );
}
about 4 years ago · Juan Pablo Isaza Report

0

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>
  );
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!