recentpopularlog in

therobyouknow : listener   7

reactjs - React—add a click listener to dangerouslySetInnerHTML sub-element - Stack Overflow
class Element extends React.Component {
state = {
loadTime: 0,
lastUpdate: 0
};

lastUpdateTimer = null;

componentDidMount() {
this.resetTimer();

this.lastUpdateTimer = setInterval(this.setLastUpdate, 1000);

this.dynamicContentElement.addEventListener("click", this.handleClick)
}

componentWillUnmount() {
clearInterval(this.lastUpdateTimer);
this.dynamicContentElement.removeEventListener(this.handleClick)
}

resetTimer() {
const now = Date.now();

this.setState({
loadTime: now,
lastUpdate: now
});
}

setLastUpdate = () => {
this.setState({
lastUpdate: Date.now()
});
}

getDynamicContent() {
const time = Math.round((this.state.lastUpdate - this.state.loadTime) / 1000);
return {
__html: `<p>
You are here: <strong>${time}</strong> seconods.
<br>
<button id="btn">Click to reset counter</button>
</p>`
};
}

handleClick = (e) => {
if (e.target.id === "btn") {
this.resetTimer();
}
}

render() {
return (
<div>
Dynamic content below:
<div
ref={el => this.dynamicContentElement = el}
dangerouslySetInnerHTML={this.getDynamicContent()}
/>
</div>
);
}
}
reactjs  react  js  javascript  computing  listener  click  onclick  element  subelement  sub  howto  web  dev  event  events 
april 2019 by therobyouknow

Copy this bookmark:





to read