sherin shaju
sherin shaju

Reputation: 179

How to add onClick event on a dynamically created button

I am trying to append a block of element everytime I receive a message. It is basically a simple chat.

So every time a new chat is received , the new message will be appended to the div.

But how I'm not able to add an onClick event to it
This is the line : <button class="likeBtn" onClick={this.pointButton}><i class="far fa-heart"></i></button>

let msgLeft = document.getElementById("msg-left");
if (this.state.username === data.username) {
msgLeft.insertAdjacentHTML(
"beforeend",
`<div class="main-c-container-right">
<div class="c-image"></div>
<div class="c-text-container">
<div class="c-name">
${data.username}
</div>
<div class="c-text"> 
<div class="c-pointer"></div>
${data.message.replace(/\n/g, "<br>")}
</div> 
<div class="c-time">
${currentTime} 
</div> 
<button class="likeBtn" onClick={this.pointButton}><i class="far fa-heart"></i></button>
</div>
</div>`
);

Upvotes: 0

Views: 136

Answers (1)

Arthur Almeida
Arthur Almeida

Reputation: 568

Basically what you need to do is to hold the array of elements somewhere (local state, redux,etc..) and display the array of elements on the JSX.

If you need to add a new element to this array, you just need to update this value with the new element and React will know how to re-render everything again.

You don't need to directly manipulate the DOM while using React.

Upvotes: 2

Related Questions