How to add js to React components in Gatsby? - reactjs

I'm trying to add the scroll function in script tags to this header component in Gatsby. I know it could work in html and not in react, but what is the right way to do it? Thanks!
import React from 'react'
import Link from 'gatsby-link'
import './header.css'
const Header = () => (
<div className='Header'>
<div className='HeaderGroup'>
<Link to='/'><img src={require('../img/logo_nav.png')} width='60' /></Link>
<Link to='/index'>Selected Works</Link>
<Link to='/uber'>Uber Thoughts</Link>
<Link to='/awards'>Awards</Link>
<Link to='/about'>About</Link>
</div>
</div>
)
export default Header
<script>
$(window).scroll(function () {
if ($(window).scrollTop() > 10) {
$('.Header').addClass('floatingHeader');
} else {
$('.Header').removeClass('floatingHeader');
}
}
</script>

If you want scripts to load before the DOM is ready you can add your scripts inside html.js file.
From the Gatsby docs:
Gatsby uses a React component to server render the and other
parts of the HTML outside of the core Gatsby application.
Read more about it here.
In your case, what you can do is to write your script inside the componentDidMount react lifecycle method, because you need access to the DOM (as you're using jQuery there) you need to run the script after the body has been loaded, so placing your script in the <head> won't work, you need to add it inside the componentDidMount method by first making your component a class component to get access to the react lifecycle methods.
import React from 'react'
import Link from 'gatsby-link'
import $ from 'jquery'
import './header.css'
class Header extends React.Component {
componentDidMount () {
$(window).scroll(function () {
if ($(window).scrollTop() > 10) {
$('.Header').addClass('floatingHeader');
} else {
$('.Header').removeClass('floatingHeader');
}
})
}
render () {
return (
<div className='Header'>
<div className='HeaderGroup'>
<Link to='/'><img src={require('../img/logo_nav.png')} width='60' /></Link>
<Link to='/index'>Selected Works</Link>
<Link to='/uber'>Uber Thoughts</Link>
<Link to='/awards'>Awards</Link>
<Link to='/about'>About</Link>
</div>
</div>
)
}
}
export default Header
You can also use a Gatsby layout template like the gatsby-starter-blog project and put your script at the bottom of the {children} call as a <script>Your script</script> and it will be available in all your pages, same as using the html.js file but since you need access to the DOM you need to put it inside the body for your script to work (more info about Gatsby layouts here).

Related

How do I embed Jobber request form in a react app

I am trying to embed a jobber request form in my react application but I am not sure how to go about this https://stackoverflow.com/questions/73739326/how-to-render-embedded-html-with-multiple-tags-in-react/73743146#73743146 has a similar question where the use of react-helmet was the solve.
I'd like for it to be button that would activate the form request. I have the button built, but not sure how to integrate the code below to make it all work.
import React from "react";
import { Helmet } from "react-helmet";
export default class Jobber extends React.Component {
render() {
return (
<div className="Application" id="f6f2802e-49e8-477b-b405-8b2b18dded97">
<Helmet>
<div id="f6f2802e-49e8-477b-b405-8b2b18dded97"></div>
<link
rel="stylesheet"
media="screen"
href="https://d3ey4dbjkt2f6s.cloudfront.net/assets/external/work_request_embed.css"
/>
<script
src="https://d3ey4dbjkt2f6s.cloudfront.net/assets/static_link/work_request_embed_snippet.js" clienthub_id="f6f2802e-49e8-477b-b405-8b2b18dded97" form_url="https://clienthub.getjobber.com/client_hubs/f6f2802e-49e8-477b-b405-8b2b18dded97/public/work_request/embedded_work_request_form"
/>
</Helmet>
</div>
);
}
}
'''
I just have a blank page.

How To Stop Link Component From Giving 404 Error in NextJS?

Can anyone tell me why the following Link Component is unable to find the linked page? VSCode is literally auto-completing the file name as I type it in but for some reason I keep getting 404.
//index.js in WelcomePage folder
import styles from "/styles/WelcomePage.module.css";
import Link from "next/link";
function WelcomePage() {
return (
<>
<h1 className={styles.title}>This is the Title</h1>
<Link href="/pages/ClassSearch">Class Search</Link>
</>
);
}
export default WelcomePage;
//index.js in ClassSearch folder
function ClassSearch() {
return <h1>The Class Search Page</h1>;
}
export default ClassSearch;
I think you need to link /ClassSearch instead of pages/ClassSearch
If you create pages/ClassSearch/index.js that exports a React component , it will be accessible at /ClassSearch
// <Link href="/pages/ClassSearch">Class Search</Link>
<Link href="/ClassSearch">Class Search</Link>
You can check , Next Page Doc
https://nextjs.org/docs/basic-features/pages

React 18: Hydration failed because the initial UI does not match what was rendered on the server

I'm trying to get SSR working in my app but I get the error:
Hydration failed because the initial UI does not match what was
rendered on the server.
Live demo code is here
Live demo of problem is here (open dev tools console to see the errors):
// App.js
import React from "react";
class App extends React.Component {
head() {
return (
<head>
<meta charSet="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<title>React App</title>
</head>
);
}
body() {
return (
<body>
<div className="App">
<h1>Client says Hello World</h1>
</div>
</body>
);
}
render() {
return (
<React.Fragment>
{this.head()}
{this.body()}
</React.Fragment>
)
}
}
export default App;
// index.js
import React from "react";
import * as ReactDOM from "react-dom/client";
import { StrictMode } from "react";
import App from "./App";
// const container = document.getElementById("root");
const container = document.getElementsByTagName("html")[0]
ReactDOM.hydrateRoot(
container,
<StrictMode>
<App />
</StrictMode>
);
The Html template shown in the live demo is served by the backend and generated using the following code:
const ReactDOMServer = require('react-dom/server');
const clientHtml = ReactDOMServer.renderToString(
<StrictMode>
<App />
</StrictMode>
)
// serve clientHtml to client
I need to dynamically generate <head></head> and <body></body> section as shown in the App class
I have been experiencing the same problem lately with NextJS and i am not sure if my observations are applicable to other libraries. I had been wrapping my components with an improper tag that is, NextJS is not comfortable having a p tag wrapping your divs, sections etc so it will yell "Hydration failed because the initial UI does not match what was rendered on the server". So I solved this problem by examining how my elements were wrapping each other. With material UI you would need to be cautious for example if you use a Typography component as a wrapper, the default value of the component prop is "p" so you will experience the error if you don't change the component value to something semantic. So in my own opinion based on my personal experience the problem is caused by improper arrangement of html elements and to solve the problem in the context of NextJS one will have to reevaluate how they are arranging their html element.
import Image from 'next/image'
/**
* This might give that error
*/
export const IncorrectComponent = ()=>{
return(
<p>
<div>This is not correct and should never be done because the p tag has been abused</div>
<Image src='/vercel.svg' alt='' width='30' height='30'/>
</p>
)
}
/**
* This will work
*/
export const CorrectComponent = ()=>{
return(
<div>
<div>This is correct and should work because a div is really good for this task.</div>
<Image src='/vercel.svg' alt='' width='30' height='30'/>
</div>
)
}
Importing and running some of the packages can cause this error too. For example, when I used Swiper.js package I encountered this problem. It's mostly because the package is using Window object somewhere.
Since it isn't a good practice to modify the content of the package itself, the best way to tackle such issues is to render the component only after the DOM is loaded. So you can try this.
const Index = () => {
const [domLoaded, setDomLoaded] = useState(false);
useEffect(() => {
setDomLoaded(true);
}, []);
return (
<>
{domLoaded && (
<Swiper>
<div>Test</div>
</Swiper>
)}
</>
);
};
export default Index;
This make the app client-side render, it's work for me:
export default function MyApp({ Component, pageProps }: AppProps) {
const [showChild, setShowChild] = useState(false);
useEffect(() => {
setShowChild(true);
}, []);
if (!showChild) {
return null;
}
if (typeof window === 'undefined') {
return <></>;
} else {
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
}
I also using NextJS, Redux Toolkit
If you're using a table, you probably missed <tbody>
incorrect:
<table>
<tr>
<td>a</td>
<td>b</td>
</tr>
</table>
correct:
<table>
<tbody>
<tr>
<td>a</td>
<td>b</td>
</tr>
</tbody>
</table>
Removing the <p> tag solved my similar problem with NEXTJS..
The error is misleading as it's not about hydration but wrongly nested tags. I figured out the conflicting tags by removing html and reloading the page until I found the problem (binary search).
In my case it was caused by <a> within <Link>. I thought next.js requires the <a> within the Link but obviously that's not/no longer the case.
See next.js documentation about <Link> tag
I have react 18.2.0 with next 12.2.4 and I fix hydration with this code
import { useEffect, useState } from 'react'
import { Breakpoint, BreakpointProvider } from 'react-socks';
import '../styles/globals.scss'
function MyApp({ Component, pageProps }) {
const [showChild, setShowChild] = useState(false)
useEffect(() => {
setShowChild(true)
}, [])
if (!showChild) {
return null
}
return (
<BreakpointProvider>
<Component {...pageProps} />
</BreakpointProvider>
)
}
export default MyApp
this issue comes in nextjs because dangerouslySetInnerHTML support only div tag. if you insert with other tag its not work.
<div dangerouslySetInnerHTML={{__html:data.description}}></div>
So let me explain why this error can occur in your NEXT JS application.
There are some tags that you can't use inside another tag.
For example you can't use div inside an anchor td tag. You can't use p tag inside a span. Same goes for other tags like table, ul etc.
You need to go to your code and remove all the invalid tags used.
In my case, I used a a tag inside span which in invalid.
This is invalid
<span>
<a target="_blank" href="https://askhumans.io"> Login </a>
</span>
This is valid.
<a target="_blank" href="https://askhumans.io"> <span> Login </span> </a>
it will work:
function MyApp({ Component, pageProps }) {
const [showing, setShowing] = useState(false);
useEffect(() => {
setShowing(true);
}, []);
if (!showing) {
return null;
}
if (typeof window === 'undefined') {
return <></>;
} else {
return (
<RecoilRoot>
<MainLayout>
<Component {...pageProps} />
</MainLayout>
</RecoilRoot>
);
}
}
export default MyApp;
here I used recoil for state managing.
If you're using NextJS and Material UI with emotion as the styling engine, then you may need to check the semantics of your components. You can find hints in the errors logged to the browser console.
Example: adding Box component inside Iconbutton will cause an error
There's no need to create a custom NextJS _document.js file because #emotion/react version 10 and above works with NextJS by default.
If u use html tags u want to place them in correct way and correct order. in NEXTJS.
ex: If u use table.
-> U must add the tbody tag
<!-- Wrong -->
<table>
<tr>
<td>Element</td>
<td>Element</td>
</tr>
</table>
<!-- Correct Way -->
<table>
<tbody> <!-- This is a Must -->
<tr>
<td>Element</td>
<td>Element</td>
</tr>
</tbody>
</table>
in Next v13 and upper you shouldn't use <a> as child inside <Link>.
if you use that, you'll get error.
in this case I use that in another way:
const Child = () => <a>hello my friend</a>
const Parent = () => {
return (
<Link href="/">
<Child />
</Link>
)
}
here I got this error, and I changed child structure for remove <a> to resolve it.
So mine is a NEXT JS app.
I am using the react-use-cart module and it seems it has issues with react #18.0.0.
I am not sure how this is possible but downgrading to react #17.0.2 removed my errors.
Previously I was using react #18.0.0
I simply ran npm uninstall react react-dom and installed versions #17.0.2.
Wahala, everything now works as expected.
I had the same issue when tried to put a div inside Card Text of React-Bootstrap.
The error can be reproduced by:
import type { NextPage } from 'next'
import { Card } from 'react-bootstrap';
...
const testPage : NextPage = () => {
...
return (
...
<Card.Text>
<div>It's an error</div>
</Card.Text>
...
)}
export default testPage
To fix it, i just removed the html tag.
I think that some react components doesn't accept html tags inside.
Make sure to wrap in Suspense the lazy modules you import.
In my case I imported
const Footer = React.lazy(() => import('../Footer/Index'));
but I was using it just like a normal module
<Footer />
I wrapped it in Suspense and the error was gone.
<Suspense fallback={<div>Loading...</div>}>
<Footer />
</Suspense>
Bottom line
If this error is given to you on the home page, try to comment some of the components you use until you find where the error is coming from.
In my case, it's an user error in nested list. I forgot adding a ul in li so it was just nested lis.
Make sure you dont have next/Link nested, I needed to refactor the code and forgod that I had a next/Link before wrapping the image.
for example
<CompanyCardStyle className={className}>
//Open Link
<Link href={route('companyDetail', { slug: company.slug })}>
<a className='d-flex align-items-center'>
<div className='company-card'>
<div className='d-flex align-items-center col-name-logo'>
<div className='company-logo'>
//Remove link and let the <a> child
<Link href={route('companyDetail', { slug: company.slug })}>
<a><img src={company.logoUrl} width={'100%'} /></a>
</Link>
</div>
<h6 className='mb-0'>{company.name}</h6>
</div>
.....
</div>
</a>
</Link>
</CompanyCardStyle>
I had this issue when I moved the pages directory in NextJs. I solved it by deleting the .next folder and rebuilding it using yarn build.
I solved this problem by NextJs dynamic import with ssr: false
import dynamic from 'next/dynamic'
import { Suspense } from 'react'
const DynamicHeader = dynamic(() => import('../components/header'), {
ssr: false,
})
export default function Home() {
return (
<DynamicHeader />
)
}
just go to browser, chrome->three bars button on top right corner->more tools->clear browsing history-> delete cookies.
no more error
i ran this piece of code and the problem went away
import "#/styles/globals.css";
import { useEffect, useState } from "react";
export default function App({ Component, pageProps }) {
const [showChild, setShowChild] = useState(false);
useEffect(() => {
setShowChild(true);
}, []);
if (!showChild) {
return null;
}
if (typeof window === "undefined") {
return <></>;
} else {
return <Component {...pageProps} />;
}
}
I had the same issue with Next.js and Faker.js, and i just use conditional rendering and it's solved. I think it happened because the values from faker.js changes twice when page first loading. Code below may help you.
`
export default function Story() {
const [avatar, setAvatar] = useState(null);
const [name, setName] = useState(null);
useEffect(() => {
setAvatar(faker.image.avatar());
setName(faker.name.findName());
}, []);
return (
<>
{avatar && name && (
<div>
<Image
src={avatar}
alt="Story Profile Picture"
width={50}
height={50}
/>
<p>{name}</p>
</div>
)}
</>
);
}
`
You Can wrap your component that cause this error with Nossr from mui(material-ui)
import NoSsr from "#mui/material/NoSsr";
<NoSsr> {your contents} </NoSsr>
to get more info: https://mui.com/material-ui/react-no-ssr/
In my case, when I used reverse() function before mapping my list, I was getting a similar error.
In my case, neither making the HTML more semantic nor modifying the _app.tsx to check if the window was loaded.
The only solution, for now, was to downgrade the React version and the React DOM.
I'm using NextJS.
I switched to version 17.0.2.
Hydration failed because the initial UI does not match what was rendered on the server
You should check the console for errors like:
Warning: Expected server HTML to contain a matching <div> in <div>.
and fix them.
Copied from https://github.com/vercel/next.js/discussions/35773
In my case, I faced this problem because I had used <img /> tag instead of Next.js <Image /> tag because I couldn't use tailwind classes with the <Image /> tag. Replacing the <img /> tag with Next.js <Image /> tag solved the issue for me. Then I wrapped the <Image /> tag with a div tag and added the classes to that.
I ran into same issue using NextJS with Material UI.
Actual solution is to use NextJS dynamic import.
In the example below do not import header component as:
import Header from "../components/header"
Instead do:
import dynamic from 'next/dynamic'
const DynamicHeader = dynamic(() => import('../components/header'), {
suspense: true,
})
Check the NextJS documentation below:
https://nextjs.org/docs/advanced-features/dynamic-import
I had this issue even with create-next-app without any changes and tried with different browser and different profiles. I see that there is no problem with them so I investigate my extensions but it didn't solve the problem. Finally I've solved it with investigating chrome dev tools settings. My problem related with "Enable Local Overrides". So I've unchecked that and it solved.
Enable Local Overrides on Chrome Settings

How to prevent re-render of react-router-dom Link component?

I am trying to limit the amounts of components that re-render on my app everytime the user clicks something. Given that the Sidebar renders regardless of which page the user is on, it seems to make sense to wrap it inside a React.memo function. This works well and the Sidebar component itself does not seem to re-render. However, the <Link> elements, which I import from react-router-dom do re-render, as do the SidebarAuthButtons and the SidebarCreateButton.
What can I do to prevent this behavior?
import React, { memo } from "react";
import { Link } from "react-router-dom";
import {
SidebarContainer,
SidebarLogo,
SidebarNav,
SidebarMenu,
SidebarListItem,
SidebarButton,
} from "../styles/SidebarStyles";
function Sidebar({ auth }) {
const SidebarAuthButtons = (
<div>
<SidebarButton>
<Link to="/login">Log In</Link>
</SidebarButton>
<SidebarButton outlined={true}>
<Link to="/register">Create Account</Link>
</SidebarButton>
</div>
);
const SidebarCreateButton = (
<SidebarButton>
<Link to="#">Create</Link>
</SidebarButton>
);
return (
<SidebarContainer>
<SidebarLogo>React Project</SidebarLogo>
<SidebarNav>
<SidebarMenu>
<SidebarListItem isHeading={true}>Menu</SidebarListItem>
<SidebarListItem>
<Link to="/">Explore</Link>
</SidebarListItem>
<SidebarListItem>
<Link to="/blogs">Blogs</Link>
</SidebarListItem>
<SidebarListItem>
<Link to="/podcasts">Podcasts</Link>
</SidebarListItem>
<SidebarListItem>
<Link to="/youtube">Youtube</Link>
</SidebarListItem>
</SidebarMenu>
{auth.isAuthenticated ? SidebarCreateButton : SidebarAuthButtons}
</SidebarNav>
</SidebarContainer>
);
}
export default memo(Sidebar);
Move SidebarAuthButtons and SidebarCreateButton outside of the functional component render scope making them into React components (currently they are just jsx saved to a variable). This should fix the rerenders.

How does webpack handle multiple files importing the same module React

I have a React app which has many components importing the same modules. Does webpack import each module once for each file requesting it, resulting in duplicate code(in this case each import twice for just the two components)? I'm considering re-writing the components so that child components do not need to require the React modules, but maybe I'm solving a problem that doesn't exist. I'd like to avoid many imports of the same react module if it results in duplicate code.
Component 1
import React from "react";
import { Link } from "react-router";
import ReactLogo from "elements/ReactLogo";
export default class MainMenu extends React.Component {
render() {
return <div>
<ReactLogo type="svg" /> <ReactLogo type="png" /> <ReactLogo type="jpg" />
<h2>MainMenu:</h2>
<ul>
<li>The <Link to="home">home</Link> page.</li>
<li>Do something on the <Link to="todo">todo page</Link>.</li>
<li>Switch to <Link to="some-page">some page</Link>.</li>
<li>Open the chat demo: <Link to="chat" params={{room: "home"}}>Chat</Link>.</li>
<li>Open the page that shows <Link to="readme">README.md</Link>.</li>
</ul>
</div>;
}
}
Component 2 importing the same 3 modules.
import React from "react";
import { Link } from "react-router";
import ReactLogo from "elements/ReactLogo";
export default class MainMenu extends React.Component {
render() {
return <div>
<ReactLogo type="svg" /> <ReactLogo type="png" /> <ReactLogo type="jpg" />
<h2>MainMenu:</h2>
<ul>
<li>The <Link to="home">home</Link> page.</li>
<li>Do something on the <Link to="todo">todo page</Link>.</li>
<li>Switch to <Link to="some-page">some page</Link>.</li>
<li>Open the chat demo: <Link to="chat" params={{room: "home"}}>Chat</Link>.</li>
<li>Open the page that shows <Link to="readme">README.md</Link>.</li>
</ul>
</div>;
}
}
No, webpack (similar to browserify and other module bundlers) will only bundle it once.
Every react component will get its own scope, and when it requires/imports another module, webpack will check if the required file was already included or not in the bundle.
So no, it will not result in duplicate code. However if you import some external packaged libraries, you may have some duplicate code. In that case, you can use Webpack's Deduplication plugin to find these files and deduplicate them. More info here for that: https://github.com/webpack/docs/wiki/optimization#deduplication

Resources