I created fresh Next.js project and only added really simple component:
const IdPanel = () => {
const [id] = useState(`${Math.random()}`);
return (
<div>
<h1 id={id} className={id}>
{id}
</h1>
</div>
);
};
When I run the dev server it throw an error in my browser "Text content does not match server-rendered HTML".
What’s the solution to fix it?
Versions:
"next": "13.0.3",
"react": "18.2.0",
"react-dom": "18.2.0"
>Solution :
As the comment suggests, id on the server doesn’t match the id on the client.
EDIT:
Simplest method is to have useState and then set the state in the useEffect
Other methods:
You can use getStaticProps or getServerSideProps to generate the random id, and then send it to the client.
In the first case, the page will be generated only once when the server starts. So when ever you try to access that page you will get the same result, because it has generated static HTML and id wont change.
In the other case the page will be generated on the server for every request to get that page. So you should get the different id each time.