0

Well I´m new to React and I'm really struggling. I have a set of buttons, each one with id asigned from result of Http request. After onClick I would want to send that id to different part of application via Router. should be relatively easy?

<Col>
  <div className="wrapper">
    <Button id={receptura.id} variant="primary" onClick={handleClick(this)}>
      Přejít
    </Button>{" "}
  </div>
</Col>

thats my button and i want smth like this

function handleClick(e) {
  alert(e.id);
};

whats the real solution to this?

konselik
  • 35
  • 8

3 Answers3

1

You need to pass the event in the onClick function like this:

onClick={(e) => handleClick(e)}

Then in your handleClick function, you can get the id from the event target like this:

alert(e.target.id);

Example: https://codesandbox.io/s/relaxed-glade-cv7ce?file=/src/App.js

samayres1992
  • 779
  • 2
  • 12
  • 30
0

It's really no different from classic JS. Except, you'll want to access the target DOM element with currentTarget instead of target key.

const id = e.currentTarget.id
0

A more Reacty way to handle it would be to use useRef() but in this case you ready have the reference of the clicked button. You can directly do:

function handleClick(e) {
    alert(e.target.id);
}

// or if you already have receptura.id in the component simply try
function handleClick(e) {
    alert(receptura.id);
}

You can read more about refs in react here How to access a DOM element in React? What is the equilvalent of document.getElementById() in React or in official docs here https://reactjs.org/docs/refs-and-the-dom.html