I'd like to add a dynamic javascript script to every page's <head>
in a react-admin app, but not sure the best way/place to do this. I've seen a lot with React-Helmet, but feel like this should be simpler than having to import something else.
I can accomplish 95% of what I'm looking to do by adding it to an HTML template that I use, but I need to inject a user id in it so needs to be on the javascript side. No code included, but looking for general guidance.
In your upmost react-admin file, generally just before the <Admin/>
component, you can have a useEffect
to add the script to head.
example:
const App = () => {
// Hooks are called before the return statement on mount on unmount.
useEffect(() => {
const script = document.createElement('script')
// You create your script here, usually by script.src = `https://${process.env.YOUR_URL_ID}`
document.head.appendChild(script)
// To delete the script on unmount
return () => {
document.head.removeChild(script)
}
}, [])
return (
<Admin>All of the Stuff</Admin>
)
}
export default App