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
This won’t work with React as it will not pass a regular
onclick
attribute through. It also makes no sense, as the recommendedonClick
can do all the same things.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.