Error: Target container is not a DOM element ( React/Nextjs) - reactjs

I have created a context component in React to return a message across all my React pages.
I am getting the error in the subject. Looked at other questions in stackoverflow but none could help me.
Here is the code:
message.js
function Message(props) {
const messageCtx = useContext(MessageBannerContext);
return ReactDOM.createPortal(
<div>
<p>Message</p>
<button>More info</button>
<button onClick={messageCtx.hideMessage}>Ok</button>
</div>,
useEffect(() => {
document.getElementById('message');
}, [])
);
}
export default Message;
_document.js
class MyDocument extends Document {
render() {
return (
<Html>
<Head />
<body>
<Main />
<DeferNextScript />
</body>
<div id="message"></div>
</Html>
);
}
}
export default MyDocument;
Any ideas why I am getting the error in the subject?

Nextjs is run in the server, so the Document Object isn't defined. I've always struggled with that, however you can try a package named jsdom.

Related

'AMP' is not defined

New to Google AMP pages. Basically, I am trying to access the AMP State to determine whether or not a div should remain hidden:
import React from 'react';
const MyButton = (props) => {
return (
<>
<Head>
<script async src="https://cdn.ampproject.org/v0.js"></script>
</Head>
<div>
<amp-state id="showHiddenContent" show="false"></amp-state>
<button
type="button"
on="tap:AMP.setState({showHiddenContent: { show: !showHiddenContent.show}})"
>
Show More
</button>
<div hidden={!AMP.getState('showHiddenContent').show}>
<p>Show this when the showHiddenContent state evaluates to true</p>
</div>
</div>
</>
);
};
export default MyButton;
I am met with the following error located on the div tag:
'AMP' is not defined
Any thoughts how I can correct this? I've added the script tag in the HEAD of the component but still get the same error. Thanks!

Could not detect external Js file in Helmet

I have started learning React and I was creating the navigation bar.
I have leftNavigationBar defined like this
const LeftNavigationBar = (props) => {
return (
<header className={share.mypage_header} id="leftcolumn">
<Helmet>
<script type="text/babel" src="../../common/js/share.js" />
</Helmet>
</header>
);
};
export default LeftNavigationBar;
but share.js did not detected.
I put require('../../common/js/share.js'); on the top and it started working and code becomes like this
require('../../common/js/share.js');
const LeftNavigationBar = (props) => {
return (
<header className={share.mypage_header} id="leftcolumn">
<Helmet>
<script type="text/babel" src="../../common/js/share.js" />
</Helmet>
</header>
);
};
export default LeftNavigationBar;
I want to know why share.js did not worked when added inside Helmet but worked when added as require on top.
Please help.

Using react context not working as expected in remix react?

Despite having seen working examples of this in non remix projects, it doesn't seem to work in the way I'm implementing it?
I have the following in root.tsx:
export const MyContext = createContext("default");
function Document({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<Meta />
<Links />
</head>
<body className="root-body">
<MyContext.Provider value="bonjour!">
<Header />
</MyContext.Provider>
{children}
<ScrollRestoration />
<Scripts />
<LiveReload />
<Footer />
</body>
</html>
);
}
export default function App() {
return (
<Document>
<Outlet />
</Document>
);
}
In my <Header/> component I have:
import { useContext } from "react";
import { MyContext } from "~/root";
export const Header = () => {
const result = useContext(MyContext);
console.log(result);
return(null)
}
The result is then that "default" is printed to the console, but surely from my understanding it should be "bonjour"?
Where am I going wrong?
The output on the server console is from Remix SSR. It does appear that the context is not being applied during server rendering. However, it does show up correctly after hydration. Unfortunately it also results in hydration errors (see browser console).
Anyway, that does seem odd. My understanding is that you can use most hooks server side (except for useEffect and useLayoutEffect).
https://codesandbox.io/s/remix-react-context-mzexmt

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 use React.Component with renderToString method?

I tried to do the server side render using renderToString method.
function handleRender(req, res) {
const html = renderToString(
<Counter />
);
res.send(renderFullPage(html));
}
function renderFullPage(html) {
return `
<!doctype html>
<html>
<head>
<title>React Universal Example</title>
</head>
<body>
<div id="app">${html}</div>
<script src="/static/bundle.js"></script>
</body>
</html>
`
}
If the component like following it works:
Counter.js
const Counter = () => {
function testClick(){
console.log('test');
}
return (
<div>
<div onClick={testClick.bind(this)}>
test
</div>
</div>
);
};
export default Counter;
However, if I change Counter.js into following:
class Counter extends React.Component {
testClick(){
console.log('click');
}
render() {
return (
<div>
<div onClick={this.testClick.bind(this)}>
test btn
</div>
</div>
)
}
}
export default Counter;
It will show errors:
Uncaught Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration.
So how to use React.Component with renderToString method?
I minimize the project and push to Github. Please have a look.
https://github.com/ovojhking/ssrTest/tree/master

Resources