Not able to attach click event to an Anchor tag inside a react component

Asked
Active3 hr before
Viewed126 times

9 Answers

clickeventcomponentreact
90%

Stack Overflow Public questions & answers ,Please note that I am trying to add onClick event to the anchor tag, which is just a static content in ComponentA and a tooltip will be created by getting static content in prop.content in ComponentB,I am beginner to react and I tried different methods to bind the click event but nothing worked out.. need help. When the user click on the anchor tag inside the tooltip with class .callFunction console.log should be printed.

React components have synthetic event listeners. All you need to do is add the onClick property to the element. So yours would look like this:

return (
       ......

        <a id="MytoolTip" ......  

       <ComponentB
          content={
            `
            <div class="share_cart_tt">
                  <a 
                  data-automation-id="..."
                  onClick={FunctionToBeCalledWhenClicked}
                  class="callFunction" 
                   > Invite </a>
            </div>
           `
          }
          target={'MytoolTip'}
          closeButton
       />

);
88%

In this tutorial, we’ll go over the basics of React’s onClick event handler, including event listening, binding methods in class components, and dealing with custom events.,When it comes to event handling in class components, binding is important, and there are a couple ways to go about it, which we covered in this tutorial.,We also reviewed some common use cases of the onClick event handler in functional components, such as updating the state, calling multiple functions, and using synthetic events.

Pretag
 Pretag team - issue, fix, solve, resolve
72%

Pretag
 Pretag team - issue, fix, solve, resolve
65%

I have an anchor tag inside my component like so:,Notice that I’m not setting state or calling any of the react functions. Is it okay if I just call a function on the onClick event of the anchor tag? Something like this:,I want to call an analytics function when user clicks on this tag like so:

class myComponent {

    render () {
        return (
            <a href="/link/to/other/page">Link</a>
        );
    }
}
load more v
75%

With JSX you pass a function as the event handler, rather than a string.,React events are named using camelCase, rather than lowercase.,For example, the HTML:

<button onclick="activateLasers()">
   Activate Lasers
</button>
load more v
40%

Before rendering anything, simply check if the state is true and assign <a> to that element, otherwise let the whole component render as it is. ,If the href attribute for the user exists, the state is set to true and the <a> tag is shown, otherwise a message is displayed. Wrap the message to be shown in a JSX element and assign that element to a variable that can be conditionally outputted. ,The same check can be performed using a ternary operator to keep the code more readable.

1 user = {
   2 name: '',
   3 email: '',
   4 sector: '',
   5 linkedinHandle: '',
   6...
   7
}
load more v
22%

The styles to apply to the link element when its route is active.,The className a <Link> receives when its route is active. No active class by default.,If true, the <Link> will only be active when the current route exactly matches the linked route.

Given a route like <Route path="/users/:userId" />:

<Link to={`/users/${user.id}`} activeClassName="active">{user.name}</Link>
// becomes one of these depending on your History and if the route is
// active
<a href="/users/123" class="active">Michael</a>
<a href="#/users/123">Michael</a>

// change the activeClassName
<Link to={`/users/${user.id}`} activeClassName="current">{user.name}</Link>

// change style when link is active
<Link to="/users" style={{color: 'white'}} activeStyle={{color: 'red'}}>Users</Link>
60%

Whenever you need to perform an action after clicking a button, link, or pretty much any element, you’ll use the onClick event handler.if(typeof __ez_fad_position != 'undefined'){__ez_fad_position('div-gpt-ad-upmostly_com-medrectangle-3-0')};,The button inside the React component has an onClick event handler attached to it, pointing to our sayHello() function. Doing so will trigger the function every time you click the button.,Therefore, the onClick event handler is one of the most powerful and most used tools in your React tool belt.

import React, { Component } from 'react';

class App extends Component {
  
  constructor(props) {
    super(props);
    this.sayHello = this.sayHello.bind(this);
  }

  sayHello() {
    alert('Hello!');
  }
  
  return (
    <button onClick={this.sayHello}>
      Click me!
    </button>
  );
}

export default App;
load more v
48%

Event delegation is where you bind the click handler not directly to the element itself, but to an element higher up the DOM tree. The idea being that you can rip out and plop in new DOM stuff inside of there and not worry about events being destroyed and needing to re-bind them.,This also prevents a situation where other JavaScript has prevented the event from bubbling up to the button itself (or higher).,I believe he is referring to adding event listeners to dynamic elements. If you’re attaching a listener to a button that doesn’t yet exist on the DOM, event delegation is a way to handle it.

Say you want to attach a click handler to a <button>. You almost surely are, as outside of a <form>, buttons don’t do anything without JavaScript. So you do that with something like this:

var button = document.querySelector("button");
button.addEventListener("click", function(e) {
   // button was clicked
});

Say our button has a gear icon in it:

<button>
   <svg>
      <use xlink:href="#gear"></use>
   </svg>
</button>

And we bind it by watching for clicks way up on the document element itself:

document.documentElement.addEventListener("click", function(e) {

});

How do we know if that click happened on the button or not? We have the target of the event for that:

document.documentElement.addEventListener("click", function(e) {
   console.log(e.target);
});

So if you were hoping to be able to do something like this:

document.documentElement.addEventListener("click", function(e) {
   if (e.target.tagName === "BUTTON") {
      // may not work, because might be svg or use
   }
});

There is a pretty decent CSS fix for this… If we make sure nothing within the button has pointer-events, clicks inside the button will always be for the button itself:

button > * {
   pointer - events: none;
}

This also prevents a situation where other JavaScript has prevented the event from bubbling up to the button itself (or higher).

document.querySelector("button > svg").addEventListener("click", function(e) {
   e.stopPropagation();
   e.preventDefault();
});

document.querySelector("button").addEventListener("click", function() {
   // If the user clicked right on the SVG, 
   // this will never fire
});
load more v

Other "click-event" queries related to "Not able to attach click event to an Anchor tag inside a react component"