1

I am trying to use native javascript in react to bind event .Actually I am getting some HTML from server .I am using dangerouslySetInnerHTML to set HTML .Now I want to bind a click event in incoming HTML from server here is my code https://codesandbox.io/s/angry-shadow-1c4v8?file=/src/App.js

 useEffect(() => {
    const alertFunc = function () {
      alert("-----");
    };
    document.querySelector(".btn").addEventListener("click", alertFunc, false);
    // Specify how to clean up after this effect:
    return function cleanup() {
      document
        .querySelector(".btn")
        .removeEventListener("click", alertFunc, false);
    };
  });
0

2 Answers 2

1

This issue is because of your template - <button className="btn">set countor </button> is redering like below.

enter image description here

So that if you try to access using class query selector, it will return undefined. You can use class instead of className.

 return {
    __html: '<button class="btn">set countor </button>'
  };

Working Code - https://codesandbox.io/s/brave-meadow-qitjb?file=/src/App.js:87-157

Sign up to request clarification or add additional context in comments.

2 Comments

it is showing error when I am printing value of counter codesandbox.io/s/serene-wright-vbeqf?file=/src/App.js
1

It's because your HTML isn't HTML. It's JSX. className is a JavaScript-only attribute.

Instead of:

<button className="btn">set countor </button>

You need:

<button class="btn">set counter</button>

1 Comment

it is showing error when I am printing value of counter codesandbox.io/s/serene-wright-vbeqf?file=/src/App.js

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.