skip to Main Content

i want to create a react component which should render a tree of nodes, in which one of the element is supposed to be an anchor. The JSX would be:

return(
  <div>
    <span>.....</span>
    <a href="someurl" onclick="javascript:....."
    ...somemore element
  </div>
);

I want to add an aatribute "onclick" to the anchor element. How can i achieve it? I don’t want to use onClick method of reactJS, which is equivalent to addEventListner method. I want to define it as attribute to anchor, so that it should appear as below in html dom tree:

<a href=".." onclick="javascript:..."

2

Answers


  1. This won’t work with React as it will not pass a regular onclick attribute through. It also makes no sense, as the recommended onClick can do all the same things.

    <a href="..." onClick={() => alert('hello')}>Link</a>
    
    Login or Signup to reply.
  2. import React from 'react';
    
    export function App(props) {
      const html = '<a onclick="javascript:alert(2)">bbb</a>';
      return (
        <div className='App'>
          <h1>Hello React.</h1>
          <h2>Start editing to see some magic happen!</h2>
          <div dangerouslySetInnerHTML={{__html: html}}></div>
        </div>
      );
    }
    

    I used this code here: https://playcode.io/react and it worked. dangerouslySetInnerHTML allows you to set the html raw, but I think it requires a parent DOM element, like the div above. I don’t know if you can do it without a parent element to set the html of.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search