score:5
after a more extensive search, i found a couple of articles with a solution. this was the first approach:
import { withprefix } from "gatsby"
import helmet from "react-helmet"
const indexpage = () => (
<div>
<helmet>
<script src={withprefix('revolution/js/extensions/revolution.extension.actions.min.js')} type="text/javascript" />
</helmet>
</div>
)
export default indexpage
this is the second approach using the gatsby-ssr.js
file:
const react = require("react")
exports.onrenderbody = ({setpostbodycomponents}) => {
setpostbodycomponents([
<script key="1" src={'js/plugins/plugins.js'} type="text/javascript" />,
<script type="text/javascript" src={"js/beauty.custom.js"}/>
]);
};
this way the scripts tags will be added at the end of the body
instead of the head
i think the second one is the best one, but have to take in count that every time you change something in the gatsby-ssr.js
file have to stop the gatsby develop
and re-run it.
in the first case usingreact-helmet
will hot-reload.
note: in both approaches, files have to be in the static
folder
here are the links to where i found this approach:
score:0
@ddieppa solution might not work if you demand your script must only be executed after the component/page is completely loaded, because:
- react-helmet always put your tag on top of the page inside the
<head>
tag, no matter where you put it. - gatsby server rendering api -
setpostbodycomponents
via (gatsby-ssr.jsx/tsx
) will append your<script>
tag at the end of the body nicely, but watch out because your script file might actually executed before react completely finishes rendering your component. if your js file is referring to any specific object in the component, you might end up seeing a bunch of null pointer exception, undefined exception.
so if you want to make sure your script file get executed/loaded right after the component is completely rendered, you might need to use either react useeffect hook (if your react component is a functional component) or react componentdidmount (if your component is a class component)
the idea will be simple, after the component is fully rendered, we will append a <script>
at the bottom of it.
with useeffect hook (for functional component)
(it's the same for componentdidmount)
import react, { useeffect } from 'react'
const mycomponent = () => {
useeffect(() => {
const mainjstag = document.createelement('script')
// given the js/main.js file is put in the static folder
mainjstag.src = 'assets/js/main.js'
document.body.appendchild(mainjstag)
console.log('component rendered!')
});
return (
<main>
<text>pretty much the component's body here...</text>
</main>
)
}
export default mycomponent
(the snippet above assuming that you put your script file under the gatsby static
folder, see gatsby - using the static folder in case you don't know about this concept in gatsby)
you can put a bunch of console.log
in both of your script file and in the useeffect/componentdidmount functions to confirm which one get executed first.
Source: stackoverflow.com
Related Query
- Including local JS and CSS files using Gatsbyjs
- import CSS and JS files using Webpack
- How to preload third-party's css and js files using webpack in ReactJS project?
- Reuse variables in all css files - using postcss-cssnext and specifically postcss-custom-properties with css-modules
- SyntaxError with Jest and React and importing CSS files
- using google fonts in nextjs with sass, css and semantic ui react
- Why are css classes are missing in production when using Tailwind and next.js?
- How to require css file using NPM and Meteor?
- How to compile TypeScript/Less files into JavaScript/CSS by using webpack and Babel?
- How to move css-in-js (Styled Components) to an external css files during build using webpack - ReactJS
- How to set component's local state while testing using jest and react-testing-library?
- Using webpack to load CSS files from node modules
- How to upload image using ReactJS and save into local storage?
- How to fix 'module not found' for audio files using file-loader? Images, CSS, and JSON are working just fine
- How can I pass CSS classes to React children and ensure they will override the child’s local class?
- ReactJs Modal Using Javascript and CSS
- Why styles don't update when saving the files in Tailwind CSS JIT mode and I need to restart the server?
- What is the difference between using extract-text-webpack-plugin and linking a merged CSS file in an HTML header?
- How to get data from local json file using actions and axios.get() (Redux)?
- Import css and sass files nextjs 7
- Separate CSS files using create-react-app code-splitting without ejecting
- SCSS files not compiling to CSS in react using Webpack
- CSS and Images files not coming after transpiling package with babel in new CRA
- Next.js pages using Link module not loading files with CSS import
- 3rd party Javascript and CSS files in Webpack. Strange behaviour
- Using external styles and multiple class names with webpack css loader
- How do I keep state persistant using local storage, react hooks, and Context Provider
- Import css files and react components in a create-react-app application?
- React - Using and loading Video files
- Build version of react app giving wrong links to CSS and JS files
More Query from same tag
- Not able to target a sub property of a JSON object in react stored in state within the render method
- React/Javascript question about async/await
- Advice on how to design a good architecture for a chat app?
- How to filter data using react?
- Jest + React Loadable error Not supported
- React custom component does not accept 2 onClicks
- Fetching and organizing data and rendering the response
- Keep MUI TextField label on top when text field has no value
- Resetting state of react-select component not working
- Update array in ReactJS
- Showing elements based on authentication status in ReactJS
- How to override child css class in parent react component using sass
- Sort method with field name passed in
- React - How to conditionally display fetched data
- Why does "Element type is invalid: expected a string" in this simple example?
- Create react app with npx that uses classes and not hooks
- React-Router How to access to useParams in custom private route
- How can I render tags from Rich Text Editor in Prismic React Client?
- how to pass the data from data.json file in react components with the help of props in react js?
- Page doesn't re-render when react context variable changes
- Why do an object key without [] will not be the accepted parameter?
- Special characters not being rendered properly across different environments
- Adding a bit of server-side dynamic client javascript to a react app
- How to access up-to-date hook state outside of setInterval closure
- Latest post first in react
- Webpack "start": "webpack-dev-server --config=config/webpack.dev.js", not working
- How to match id key from two JSON files then update the source JSON with changes
- Modal Component doesn't update even though data is sourced from useContext, where the Array is updated by the useReducer Hook
- TypeScript, React and Gulp.js - defining react
- How to use svelte store with react.js