Cohchi
Cohchi

Reputation: 563

.click doesn't work in reactjs

I'm trying to do an accordion in jquery in a react project. In the public / index.html, I included my public file / main.js and jquery and in the main.js file I put this function

jQuery(document).ready(function(){
$('h2').click(function(){
alert('okay');
})
}

but it does not work, however, if I replace h2 by body, when I click somewhere the alert works. After several tests, I ended up thinking that it was because of the loading of the script In fact, the h2 does not exist at first, then Reactjs does the work, fetching data from firebase and displaying it. The h2 are displayed at this time. So I think my script does not find the h2 tag What do you think ? How do I have to make it work?

Upvotes: 0

Views: 44

Answers (1)

Dario
Dario

Reputation: 6280

I would do:

$("body").on("click", "h2", function() { alert("okay"); })

in this way you listen to click events on body (which exists from the initial loading) and then execute this particular handler only for h2 tags (which can be added later dynamically).

Upvotes: 1

Related Questions