Events using React Js

<body>
  <button id="btnId">Click Me!</button>
</body>
I have this html code above and I want to add a click event on the button with the id "btnId" using react js...how will i do that without updating that button...

Upvotes: 0

Views: 70

Answers (2)

Arun Yokesh
Arun Yokesh

Reputation: 1354

You can bind events in 2 ways

1. https://stackoverflow.com/a/51474887/4270123

2. Here is the example

class Button extends React.Component {

 handleClick(e) {
   e.preventDefault();
   console.log(e.target.id);
   alert("#" + e.target.id + " is clicked"); 
 }

 render() {
   return (
     <button onClick={ (e) => this.handleClick(e) } id="btnId">
       Click Me!
     </button>
   );    
  }
}

Upvotes: 1

marmeladze
marmeladze

Reputation: 6564

Below code might give you an idea.

class Button  extends React.Component {

 constructor(props) {
    super(props);
    this.handleChange = this.handleClick.bind(this);
 }

 handleClick(e) {
   e.preventDefault();
   alert("I am clicked"); 
 }

 render() {
   return (
     <button onClick={this.handleClick}>
       Click Me!
     </button>
   );    
  }
}

Upvotes: 0

Related Questions