I'm using the typewriter-effect library in Next.js, but it's causing this error:
Error: Hydration failed because the initial UI does not match what was rendered on the server.
I followed the explanation in the documentation to fix the error trying to add the Typewriter inside a state by useEffect when the component rendered, but it didn't work. I cannot understand why this error is being caused.
My code: //TypeEffect.tsx
import Typewriter from 'typewriter-effect';
const TypeEffect = () => {
const strings = [
'modern & innovative digital solutions.',
'e-commerces, web systems, landing pages, blogs & much more.',
'front-end & back-end development.',
'UX &UI best pratices.',
];
return (
<Typewriter
options={{
autoStart: true,
loop: true,
}}
onInit={(typewriter) => {
typewriter
.typeString(strings[0])
.pauseFor(4000)
.deleteAll()
.pauseFor(2000)
.typeString(strings[1])
.pauseFor(4000)
.deleteAll()
.pauseFor(2000)
.typeString(strings[2])
.pauseFor(4000)
.deleteAll()
.pauseFor(2000)
.typeString(strings[3])
.pauseFor(4000)
.deleteAll()
.pauseFor(2000)
.start();
}}
/>
);
};
export default TypeEffect;
//Content.tsx
import React from 'react';
import TypeEffect from '../TypeEffect';
const Content = () => {
return (
<main className='mx-auto px-2 select-none font-anton md:-translate-y-24 md:-translate-x-24'>
<h1 className='text-6xl md:text-7xl mb-4'>
creative developer
<span className='text-primary'>.</span>
</h1>
<p className='font-montserrat absolute font-regular md:text-2xl'>
{TypeEffect()}
</p>
</main>
);
};
export default Content;
This is because you have nested your {TypeEffect()} content inside paragraph <p> tags inside Content.tsx. This is a known problem with next.js. There's an issue on it. In the issue, they conclude that because nesting stuff inside p tags isn't valid HTML they won't fix it.
If you make the p tags into div tags the problem goes away:
<div className='font-montserrat absolute font-regular md:text-2xl'>
{TypeEffect()}
</div>
This has nothing to do with the typewriter-effect library, by the way. You get the same error if you nest an empty div inside the same p tag in the original code and don't use typewriter-effect at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With