Last active
April 29, 2021 15:28
Star
You must be signed in to star a gist
react dangerouslySetInnerHTML callback https://stackoverflow.com/questions/44550462/reactjs-callback-for-dangerouslysetinnerhtml-complete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8" /> | |
<title>Hello World</title> | |
<script src="https://unpkg.com/react@17/umd/react.development.js"></script> | |
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> | |
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> | |
</head> | |
<body> | |
<div id="root"></div> | |
<script type="text/babel"> | |
class ContentRenderer extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = {n: 0}; | |
this.handleClick = this.handleClick.bind(this); | |
} | |
componentDidMount() { | |
this.observer = new MutationObserver((mutationRecords) => { | |
mutationRecords[0].target.addEventListener('click', (e) => { | |
alert(1); | |
}); | |
}); | |
this.observer.observe(this.myElement, { | |
childList: true, | |
attributes: true, | |
characterData: true | |
}); | |
} | |
componentWillUnmount() { | |
this.observer.disconnect(); | |
} | |
handleClick() { | |
this.setState((state, props) => ({ | |
n: state.n + 1 | |
})); | |
} | |
render() { | |
return ( | |
<div> | |
<div onClick={this.handleClick}>Click me</div> | |
<div | |
dangerouslySetInnerHTML={{ __html: "<div>" + this.state.n + "</div>" }} | |
ref={(myElement) => { this.myElement = myElement; }} | |
/> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render( | |
<ContentRenderer/>, | |
document.getElementById('root') | |
); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment