0

<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...

6
  • Can you elaborate? What do you mean by dynamically? Commented Jul 23, 2018 at 8:10
  • by using class ex. class Sample extends React.Component{render(){ return(<button onClick={this.someFunction}>Click</button>)}} Commented Jul 23, 2018 at 8:15
  • Please EDIT your question and add more details to it instead of posting comments to your own question. Thanks Commented Jul 23, 2018 at 8:18
  • 1
    @KreeshianAlvirGutierrez you can use addEventListener just like in vanilla javascript inside componentDidMount(). Commented Jul 23, 2018 at 8:20
  • @Chris I got it, thank you for the answer I thought that componentDidMount() was used for making api calls. Commented Jul 23, 2018 at 8:37

2 Answers 2

1

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>
   );    
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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>
   );    
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.