Home > Blockchain >  React dangerouslySetInnerHTML onClick not working
React dangerouslySetInnerHTML onClick not working

Time:11-09

Hi I am very new to react just trying to add onClick inside the html render by the dangerouslySetInnerHTML

Here is the code example

import "./styles.css";
import React from "react";

export default function App() {
  const hello = (event) => {
    alert("hello", event.target);
  };
  const displayUrl = () => {
    const str = `<a onClick=${hello} href="#">Test</a>`;
    return <div dangerouslySetInnerHTML={{ __html: str }} />;
    //return `<a href='#'>Test</a>`;
  };

  return (
    <div className="App">
      <React.Fragment>{displayUrl()}</React.Fragment>
    </div>
  );
}

Codesandbox example

Please help me to understand why it's not working

CodePudding user response:

You're setting an onClick listener, which is React in HTML. To run javascript after a click event, you're better off using the <button> element.

Try something like this:

const displayUrl = () => {
  const str = ` <button onclick="${hello}">Click me</button> `
  return <div dangerouslySetInnerHTML={{ __html: str }} />
};

Please keep in mind that using dangerouslySetInnerHTML isn't best practice. I would follow Henry Woody's answer.

CodePudding user response:

As pointed out in the comments (and as indicated by the property name), you should avoid using dangerouslySetInnerHTML as much as possible (I would say don't use it at all until you understand React very well). Here there is a straightforward React approach to setting the onClick function on an element.

You need to render the element with the onClick normally and just pass onClick as a prop.

For example:

import React from "react";
import "./styles.css";

export default function App() {
  const hello = (event) => {
    alert("hello", event.target);
  };

  return (
    <div className="App">
      <button onClick={hello}>Click here</button>
    </div>
  );
}

With a link (as your sandbox has and question suggests), you can use the a element and set the href to the desired URL.

For example:

import React from "react";
import "./styles.css";

export default function App() {
  const url = "http://example.com"

  return (
    <div className="App">
      <a href={url}>Click here</a>
    </div>
  );
}

And url can come from anywhere you'd like (e.g. props or fetched from somewhere and held in state).

  • Related