JGPcode
JGPcode

Reputation: 167

How can I access the value of this event in react?

I would like to be able to access the value of an input, normally I usually retrieve it with event.target.value but this time it is not possible since the event.target path throws me a li element:

enter image description here

It is a component of the material UI library:

<MenuItem
  onClick={handleItemValue}
  value={"VALUE TO RECOVER"}
>
 Option Text
</MenuItem>

Upvotes: 0

Views: 74

Answers (2)

Chris Haupt
Chris Haupt

Reputation: 152

The value prop is usually used to set the value, not to read it. I would recommend the useRef hook if this is a functional component:

let menuItemRef = React.useRef(null);

<MenuItem
   ref={menuItemRef}
>
     Option Text
</MenuItem>

If you need to get the text contained within the element on click, you can use innerText like so:

<MenuItem
   ref={menuItemRef}
   onClick={()=>console.log(menuItemRef.current.innerText)}
>
     Option Text
</MenuItem>

Not sure what you want to do with the value on click, but this will log it to the console. Basically, you can find the string in an element like <li> or <p> by creating a ref and then calling refName.current.innerText

Upvotes: 1

Mahdi Rasti
Mahdi Rasti

Reputation: 67

here an example for you:

const handleItemValue = (value) => {
   //you can access to `value`
}

<MenuItem
   onClick={() => handleItemValue("VALUE TO RECOVER")}
>
  Option Text
</MenuItem>

Upvotes: 1

Related Questions