Can't Use Next/Link with NextJs 13 app directory - reactjs

when i enable nextjs 13 appDir feature and add a Link i get and error of
" Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'call') "
in the console i also see another error
" Uncaught Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering. "
here is my code
import Link from 'next/link';
function Header() {
return (
<div>
<Link href="/">Home</Link>
</div>
);
}
export default Header;
inside the appDir i have
layout.tsx
page.tsx
head.tsx
Header.tsx
i havnt yet changed anything in any of them expect that i added the Header component in the layout.tsx
import Header from './Header';
import '../styles/globals.css';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html>
<head />
<body>
<Header />
{children}
</body>
</html>
);
}
ONLY WHEN I AM ADDING 'LINK'
if im not using the appdir and using good old ./pages it's fine..
what's wrong here ? because i saw many tutorials and im just copying and pasting i also get the same error when adding Link

Related

Hydration error in Next.js 13 (Video included)

I created a new next app and installed the newest version. I am testing out the app dir and encountered an error.
When I continually switch between the about and contact page and refresh the page at the same time like in this video
This error shows up
This only happens if the Footer component is added. If I remove the Footer component this will not happen
app/about/page.js
import Link from 'next/link'
import { Footer } from '../Footer'
export default function Page() {
return (
<>
<Link href="/about">about</Link>
<Link href="/contact">contact</Link>
<Footer />
</>
)
}
app/contact/page.js
import Link from 'next/link'
import { Footer } from '../Footer'
export default function Page() {
return (
<>
<Link href="/about">about</Link>
<Link href="/contact">contact</Link>
<Footer />
</>
)
}
app/footer.jsx
export function Footer() {
return (
<footer>Footer</footer>
)
}
Github Repo
I was able to reproduce the error after following the OP's instructions to refresh quickly ("spam refresh") several times.
I am able to solve the error by making the Footer component exported in Footer.jsx a default export, rather than named export.
Simply change the function in Footer.jsx to read:
export default function Footer() {
...
}
And update the Footer imports within the pages, i.e.
// app/about/page.js
import Footer from '../Footer'
...
// app/contact/page.js
import Footer from '../Footer'
...
🌶️ The ... ellipses are for example, obviously not legitimate JavaScript! Replace with your code.

i keep getting the same error when i try to import an image wheter its png,jpg or svg. module not found: cant resolve?

import React from "react";
import logo from "./logo.svg"
function NavBar() {
return (
<div className="navBar">
<button>Manual</button>
<button>Scenarios</button>
<button><img src={logo}/></button>
<button></button>
<button></button>
</div>
);
}
export default NavBar;
I am getting this:
Compiled with problems:
ERROR in ./src/components/NavBar.jsx 5:0-30
Module not found: Error: Can't resolve './logo.svg' in 'C:\Users\andri\Documents\myReact\rushing-ranges\src\components'
I have tried importing from folder images and also from root of src directory.
use require keyword when giving path
<img src={require('./logo.svg')}/>

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

Gatsby: Accessing props array's length in a component leads to TypeError (property undefined)

Problem
In index.js I passed a modifier prop with the value of ["fullWidth", "secondMod"] to the imported Container sub-component:
index.js
<Container>
<h1>Hi people</h1>
<p>Welcome to your new Gatsby site.</p>
<p>Now go build something great.</p>
</Container>
// Modifier Prop comes here
<Container modifier={["fullWidth", "secondMod"]}>
<Img fluid={data.placeholderImage.childImageSharp.fluid} />
</Container>
Over in container.js, I want to access the array in the console.log:
container.js
import React from "react"
import PropTypes from 'prop-types';
// Styles
import container from "../styles/components/container.module.scss"
const Container = (props) => {
console.log(props.modifier.length); // TypeError: Cannot read property 'length' of undefined
console.log(props.modifier); // (2) ["fullWidth", "secondMod"]
console.log(props.children.length); // 3
return (
<section className={container.section}>
<div className={`${container.container} ${props.modifier}`}>
{props.children}
</div>
</section>
)
}
export default Container
Nonetheless, the first console.log(props.modifier.length) throws an error. The error's page tite is saying:
TypeError: Cannot read property 'length' of undefined
Same e.g. for using props.modifier[0].
Problem Source
Thanks to the comment of #PompolutZ, the problem for the error is the first <Container> in index.js. Since it does not pass a modifier prop, props.modifier and props.modifier.length are undefined.
Solution needed
Following the Problem Source, I don't know what is Best Practice for differentiating between sub-components (here <Container>) that pass a prop and those which don't. I still want to process the props, but don't want React to throw an error, if there is one that didn't pass a prop.
Using defaultProps can prevent React from throwing an Error. In this case that would mean to add the following code to container.js after the closing bracket (}) of const Container and before export default Container:
Container.defaultProps = {
modifier: [],
}
Also see the React Documentation on default Props for that.
I would have written it like this (container.js):
import React from "react"
import PropTypes from 'prop-types';
// Styles
import container from "../styles/components/container.module.scss"
export default ({ children, modifier = [] }) => {
console.log(modifier && modifier.length);
console.log(modifier && modifier);
console.log(children && children.length);
return (
<section>
<div>{children}</div>
</section>
);
};

Resources