inquisitivemongoose
inquisitivemongoose

Reputation: 396

Button's onclick records the i tag instead of the button itself

I have a button and I want to capture its 'id' when it is clicked.

<button id={props.id} 
   onClick={props.handleClick} 
   className="btn btn-circle" >
   <i class="fas fa-angle-down"></i>
</button >

When I log the event console.log(event.target.id); in my handleClick function, it returns the i tag's 'id' (which is just an empty string) if I click in the middle of the button. If I click on the sides of the button, then my handleClick function works as intended.

This is what the button looks like for reference enter image description here

How should I fix this? I suppose I can add the same 'id' attribute to the i tag, but was wondering if there was a better fix.

Upvotes: 0

Views: 160

Answers (2)

trysetyoutomo
trysetyoutomo

Reputation: 346

you also can use this way to get id value

import { render } from "react-dom";
import React, { Component } from "react";
import "./styles.css";

class Click extends Component {
  constructor(props) {
    super(props);
  }

  click(e) {
    let id = e.target.attributes.getNamedItem("id").value;
    alert(id);
  }

  render() {
    return (
      <button onClick={this.click} id="This is id">
        Click Here
      </button>
    );
  }
}
export default Click;

Upvotes: 0

Ryan Le
Ryan Le

Reputation: 8412

You could use currentTarget instead:

console.log(event.currentTarget.id);

This will return the currentTarget that you have attached your onClick function on, not the target that triggers the event.

Upvotes: 2

Related Questions