I've been playing around with some libraries and tested out react-text fun. I placed the blotter script in my html file and installed the library. When I test out an effect, I get two rendered elements on my page. Any ideas on how to fix this?
public HTML:
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="https://unpkg.com/blotterjs-fork#0.1.0/build/blotter.min.js"></script>
</body>
component:
import React from 'react'
import { LiquidDistortionText } from 'react-text-fun'
// styles
import { Header, HeroContainer } from './Home.styles'
// components
export default function Home() {
return (
<Header>
<HeroContainer>
<LiquidDistortionText
text="Text"
speed={0.25}
rotation={0.2}
distortX={0}
distortY={0.2}
noiseAmplitude={0.1}
noiseVolatility={1}
/>
</HeroContainer>
</Header>
)
}
rendered webpage
Everything looks correct. You should look at your Header Component and HeroContainer. Maybe you used children twice times.
I have a problem with gatsby 5, it imports jquery and slick.js to it using "Helmet" without refreshing the page, the script works but as soon as I click f5 (clear the cache), I suddenly get an error that "$ is not defined" or that "jquery s not defined"I feel that it may be a fault that they will not load in the correct js order, but I might be wrong. Will you help?
export function Head() {
return (
<>
<title>Simtopia</title>
<Helmet>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"
integrity="sha512-XtmMtDEcNz2j7ekrtHvOVR4iwwaD6o/FUJe6+Zq+HgcCsk3kj4uSQQR8weQ2QVj1o0Pk6PwYLohm206ZzNfubg=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
<script
src="/js/localJS.js"
></script>
</Helmet>
</>
)
}
If you are loading scripts that are mutually dependent I'd recommend using the Script API that Gatsby provides, which exposes an onLoad callback:
import React, { useState } from "react";
import { Script } from "gatsby";
export function Head() {
const [loaded, setLoaded] = useState(false);
return (
<>
<Script
src="https://code.jquery.com/jquery-3.6.0.min.js"
onLoad={() => setLoaded(true)}
/>
{loaded && (
<Script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js" />
)}
{loaded && (
<Script src="/js/localJS.js" />
)}
</>
);
}
Note: tweak the order or the conditions accordingly
⚠️
Outside the scope of the question: don't import jQuery inside React apps, or you will break the hydration. Really, don't do it.
React (so Gatsby) creates and manipulates a virtual DOM (vDOM) while jQuery manipulates directly the real DOM. Using both will cause unwanted (re)hydration issues because when something changes in the DOM React won't be aware and vice-versa. This translates into multiple issues, but one of the most typical is finding unstyled parts of the page, non-rendered hooks when moving forward/backward using browser's arrows/history, etc.
From React docs:
React is unaware of changes made to the DOM outside of React. It
determines updates based on its own internal representation, and if
the same DOM nodes are manipulated by another library, React gets
confused and has no way to recover.
Alternatively, use React-based approaches such Reack Slick or using useRef hook when pointing DOM elements
I recently discovered React and I'm trying to understand how it works.
I put this code:
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>Hello World</h1>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
Super simple, but my page is blank instead of showing h1 element I suposedly rendered here.
Can someone explain why doesn't it work and what am I missing to make it work?
There is also a simple element in the HTML file along with all instructed code from the React doc page:
<div id="app"></div>
<script
src="https://unpkg.com/react#18/umd/react.development.js"
crossorigin
></script>
<script
src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"
crossorigin
></script>
<script src="index.js"></script>
Stack Snippet:
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>Hello World</h1>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
<div id="app"></div>
<script
src="https://unpkg.com/react#18/umd/react.development.js"
crossorigin
></script>
<script
src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"
crossorigin
></script>
I suspect you don't have anything in place to handle JSX. Note that <App /> is invalid JavaScript syntax. It's a JavaScript extension called JSX. You don't have to use JSX with React, but most people do.
If you want to use JSX, you'll need to use Babel or similar to compile (aka "transpile") the JSX into calls to React.createElement. Usually you do that as a build step so that what's deployed is already transpiled (and minified and bundled). There is an in-browser way of doing it with Babel Standalone, but it's (strongly) not recommended for production. (This meta question shows using Babel standalone.)
I´m a newbie on react and gatsby but i´m working on a little project as practice anda I have a little problem. I want to add a custom JS file to the project (little functions for a calculator on the index). I used Helmet to import them and on develop enviroment is working fine, but once build, is not.
import Helmet from "react-helmet"
import { withPrefix, Link } from "gatsby"
export default function homePage() {
return (
<main>
<Helmet>
<script src={withPrefix('/functions.js')} type="text/javascript" />
<script src={withPrefix('/escritura.js')} type="text/javascript" />
</Helmet>
}
I´m not sure what I am doing wrong. Someone can help me, please? You can see the project proof version live here:
https://modest-hoover-aac2d1.netlify.app/
In the final version, every input should be filled automatically, but is not happening.
withPrefix is a helper function that only works in build mode because in development mode paths don't need to be prefixed:
For pathnames you construct manually, there’s a helper function,
withPrefix that prepends your path prefix in production (but doesn’t
during development where paths don’t need to be prefixed).
So if your code works well under development mode, just remove withPrefix and leave your code as:
export default function homePage() {
return (
<main>
<Helmet>
<script src={`/functions.js`} type="text/javascript" />
<script src={`/escritura.js`} type="text/javascript" />
</Helmet>
}
I'm a total React newbie and I guess there is something fundamental I don't quite understand here. A default Gatsby page looks like this. Is there a way to use a local .js file somewhat like this?
<script src="../script/script.js"></script>
What I would like to achieve is to have react ignore script.js but still have the client side use it. A default Gatsby page looks like this, is it possible to do somerthing like that there?
import React from "react"
import { Link } from "gatsby"
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
const IndexPage = () => (
<Layout>
<SEO title="Home" keywords={[`gatsby`, `application`, `react`]} />
<h1>Hi people</h1>
<p>Welcome to your new Gatsby site.</p>
<p>Now go build something great.</p>
<div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
<Image />
</div>
<Link to="/page-2/">Go to page 2</Link>
</Layout>
)
After several hours of frustration I finally stumbled upon discussion on GitHub that solved this for me. In Gatsby, there is a thing called static folder, for which one use case is including a small script outside of the bundled code.
Anyone else in the same situation, try proceeding as follows:
Create a folder static to the root of your project.
Put your script script.js in the folder static.
Include the script in your react dom with react-helmet.
So in the case of the code I posted in my original question, for instance:
import React from "react"
import Helmet from "react-helmet"
import { withPrefix, Link } from "gatsby"
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
const IndexPage = () => (
<Layout>
<Helmet>
<script src={withPrefix('script.js')} type="text/javascript" />
</Helmet>
<SEO title="Home" keywords={[`gatsby`, `application`, `react`]} />
<h1>Hi people</h1>
<p>Welcome to your new Gatsby site.</p>
<p>Now go build something great.</p>
<div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
<Image />
</div>
<Link to="/page-2/">Go to page 2</Link>
</Layout>
)
Notice the imports
import Helmet from "react-helmet"
import { withPrefix, Link } from "gatsby"
and the script element.
<Helmet>
<script src={withPrefix('script.js')} type="text/javascript" />
</Helmet>
This would have saved hours of my time, hopefully this does it for someone else.
There are many ways to add scripts in GatsbyJS...
To execute a script on a specific page
create a stateless ScriptComponent.js file and place it inside your /src folder.
in your ScriptComponent.js use require() to execute the script inside useEffect() like this:
const ScriptComponent = ({
src, // if internal,put a path relative to this component
onScriptLoad = () => {}, // cb
appendToHead = false,
timeoutDuration = 10,
defer = false,
isExternal = false,
}) => {
useEffect(() => {
setTimeout(() => {
if (isExternal) {
const script = document.createElement('script');
script.src = src;
script.onload = onScriptLoad;
defer
? script.defer = true
: script.async = true;
appendToHead
? document.head.appendChild(script)
: document.body.appendChild(script);
} else { // for internal scripts
// This runs the script
const myScript = require(src);
}
}, timeoutDuration);
}, []);
return null;
};
To run it on client-side, you could check the window object inside your script.js file if you didn't run it in useEffect:
if(typeof window !== 'undefined' && window.document) {
// Your script here...
}
finally, go to the page you want to execute the script in it (e.g. /pages/myPage.js ), and add the component <ScriptComponent />
If you want to execute a script globally in (every component/page) you could use the html.js file.
first, you'll have to extract the file (in case you didn't) by running:
cp .cache/default-html.js src/html.js
inside your html.js file:
<script dangerouslySetInnerHTML= {{ __html:`
// your script here...
// or you could also reuse the same approach as in useEffect above
`}} />
Just create gatsby-ssr.js file on root folder
and add the following pattern for your scripts folder
import React from 'react'
export const onRenderBody = ({ setPostBodyComponents }) => {
setPostBodyComponents([
<script
key="https://code.jquery.com/jquery-3.2.1.slim.min.js"
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossOrigin="anonymous"
defer
/>,
<script
key="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossOrigin="anonymous"
defer
/>,
<script
key="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossOrigin="anonymous"
defer
/>
])
}
Then, you at the end of dom you'll see the links to scripts
If you'd like to use a Gatsby plugin, which to me is no different from using an external library like Helmet (plugins are npm packages after all), you could use gatsby-plugin-load-script.
You can provide either the url to the src attribute or a local path. If you're going to store your JS in a local file such as some-minified-js.min.js - make sure to store in the static directory at the root of your project.
Once you do this, you can access via the global object:
global.<object or func name here>
For example, I was trying to include a very small JS library via a minified file, so I stored the file in /static/my-minified-library.min.js and then:
Installed the plugin: npm i --save gatsby-plugin-load-script
Added this to my gatsby-config.js
plugins: [
{
resolve: "gatsby-plugin-load-script",
options: {
src: "/my-minified-library.min.js",
},
},
],
Accessed in my react component like so:
useEffect(() => {
const x = new global.MyImportedLibraryObject();
}, []}
Gatsby uses html.js in the src folder. Not index.html like most react projects.
Example html.js file:
import React from "react"
import PropTypes from "prop-types"
export default class HTML extends React.Component {
render() {
return (
<html {...this.props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
{this.props.headComponents}
</head>
<body {...this.props.bodyAttributes}>
{this.props.preBodyComponents}
<div
key={`body`}
id="___gatsby"
dangerouslySetInnerHTML={{ __html: this.props.body }}
/>
{this.props.postBodyComponents}
</body>
</html>
)
}
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
}
For adding custom Javascript using dangerouslySetInnerHTML inside src/html.js:
<script
dangerouslySetInnerHTML={{
__html: `
var name = 'world';
console.log('Hello ' + name);
`,
}}
/>
You can try adding your js there but, note that your js may not work as expected. You can always look into react-helmet for more dynamic apps and adding scripts to <head>.
Gatsby Documentation: https://www.gatsbyjs.org/docs/custom-html/
You can do this very easily with the Gatsby plugin "gatsby-plugin-load-script."
Simply do this:
Create a folder named static at the root of your gatsby app
Place your script in it
Add the following configuration in gatsby-config.js
{
resolve: 'gatsby-plugin-load-script',
options: {
src: '/test-script.js', // Change to the script filename
},
},
I'm not sure if anyone still needs this answer, but here it goes:
The answer by Elliot Marques is excellent. If you need it for a local file, upload the script to Github and use a service like JSDelivr. It saves a lot of time and stress.
React works with dynamic DOM. But for rendering it by browser, your web server should send a static index page, where React will be included as another script tag.
So, take a look on your index.html page, which you can find in public folder. There you could insert your script tag in the header section, for example.