run function once but globally in react
when i make webpage, one thing i generally do is set all the divs to a random color using js for better understandng
now that i am using react. im confused how to do it
my react project goes like this
i have a
Main.jsx
that renders App.jsx
App.jsx
has a main
tag , inside which i have LeftSection
and RightSection
component
the LeftSection
component has its own components that have their own jsx file
now i can write a function that that gets all the divs using querySelectorAll()
and loops through the arr and set random color to them, but when i make the function in App.jsx
and call it there it only sets random color to the main tag cause App.jsx
only has main tag in it inside which it has components. I thought since it has LeftSection
and RightSection
which have rest of the divs inside of them but ofc in their own component file, i thought the function might effect that as well
now one solution that i have is to make a Helper.js
which will have have the coloring function expoted and i'll import it in all my jsx and run the function
but that requires me to do the same thing multiple times for ALL the jsx files . is there any way i can basically call the function once somewhere globally and it'll effect all the jsx files so i dont need to repeat myself
or if there's any better way then I'm all in for it tnx ❤️4 Replies
Don''t know if there is a more suitable solution, but you could ad an extra script tag add the end of your index.html
sorry for late response
I've tried this, I've tried added a script at then end of body in html
it's basically the same thing. it can't access the divs that were declared inside react components
but one thing is that if I run the function that colors the div after say 3 or 4s using setTimeOut , THEN it can access the divs
so apparently, what I can understand is, normal js fine runs before jsx files run or perhaps js file is fetched before jsx files are ( i guess for it having less code hence space? )
but I can't wait for 3 to 4 sec every time im previewing the page
i did end up exporting importing helper.js in every jsx file. that sorta worked
but having a global one would've helped better
I think you can create a custom hook and call it on the pages, or even use it globally
hmm.. well I've only started react so i haven't got to that level yet in fact I've just started practicing useEffect() xD
but I'll keep it in mind tnx xD
all tho, i did have another idea that popped in my mind
that is, since js runs becomr react components load in, ig i can basically make a setInterval that checks if a particular div or an element had loaded or not, and then basically clear interval and run coloring function when they load
this may work, haven't tried yet