How to get the value of custom atttributes in react hooks?

Viewed 106

How do I get the value of custom attributes using react hooks?

Here is sample code in code sandbox : demo live

code

import "./styles.css";
import React, { useState } from "react";

export default function App() {
  const [value, setValue] = useState("");

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <select
        onChange={(e) => {
          console.log("value", e.target.value);
          console.log("description", e.target.description);
          setValue(e.target.value);
        }}
        name="cars"
        id="cars"
      >
        <option value="volvo" description="hahahahaa">
          Volvo
        </option>
        <option value="saab" description="hehehehehe">
          Saab
        </option>
        <option value="opel" description="hoooooooo">
          Opel
        </option>
        <option value="audi" description="huuuuuuuuuu">
          Audi
        </option>
      </select>
    </div>
  );
}

I am able to get the value of attribute value but not the custom description. I get undefined console.log("description", e.target.description);

What is wrong here?

2 Answers

In your example target is the <select> and you would need to traverse to the selected option and get the attribute value.

It really doesn't seem practical to store data in a custom option attribute when you could use a hashmap with values as keys

const Example = () => {
  const [desc, setDesc] = React.useState('')
  
  const descriptions = {
     volvo:'hahahahaa', 
      saab:'hehehehehe',
      opel:'hoooooooo'
  }
  
  const handleChange = (e)=>{
    const val =  e.target.value,
          des = descriptions[val]
     console.clear()
     console.log("value",val);
     console.log("description", des);
     setDesc(des)
  }

  return (
    <div>
    <div>Description: {desc}</div>
      <select
    onChange={handleChange}
    name="cars"
    id="cars"
  >
    <option value="volvo">
      Volvo
    </option>
    <option value="saab">
      Saab
    </option>
    <option value="opel" >
      Opel
    </option>  
  </select>
  
    </div>
  );
};

// Render it
ReactDOM.render(
  <Example title="Example using Hooks:" />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

e.target give you the select tag, you can get the option tag and the description like this:

console.log("description", e.target.childNodes[e.target.selectedIndex].getAttribute("description"));
Related