React JS get Tag Name and Inner Text on Click

When the button element is clicked, the click event gets triggered, the value of the tagName property can be used to find out HTML element the source of the event and innerText property can be used to find out text written in that HTML element.

Create React App

Type the following command to create a new react app:

npx create-react-app demo

Now, go to the project folder:

cd demo

Now, update default App.js with below code snippet

src\App.js

import React, { Component } from 'react';
 
class App extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
 
  handleClick = (event) => {
      alert(event.target.innerText);    // Click Me
      alert(event.target.tagName);      // BUTTON
  }
 
  render() {
    return (
      <div>
        <div className="text-center">
          <button className="btn btn-secondary" onClick={this.handleClick}>
            Click Me
          </button>
        </div>
      </div>
    );
  }
}
 
export default App;
Most Helpful This Week