search

Home  >  Q&A  >  body text

React hydration error in Next.js - "Expected server HTML to contain <a> tag matching <a> tag"

I am working on a Next.js project, but I keep encountering a hydration error. The specific error message I saw was:

Error: Hydration failed because the initial UI does not match what is rendered when rendered on the server side.

Warning: Expecting server HTML to contain matching <div>.

I understand this may be due to a mismatch between the server-side rendering (SSR) HTML and the HTML generated by React during hydration on the client side. Warning: A <div> tag was expected in the server-rendered HTML, but was not found.

import React from 'react';
import styled from 'styled-components';
import {
  FaIcon1 as Icon1,
  FaIcon2 as Icon2,
  FaIcon3 as Icon3,
  FaIcon4 as Icon4
} from 'react-icons/fa';
import Link from 'next/link';

const Container = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #ffffff;
`;

const ListItemContainer = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  width: 70%;
  overflow-y: auto;

  @media (min-width: 768px) {
    flex-direction: row;
  }
`;

const ListItem = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 10px;
  margin: 10px 10px;
  font-size: 1.8em;
  border: 1px solid #299d51;
  border-radius: 5px;
  cursor: pointer;
  color: #14080e;
  transition: background 0.3s;
  width: 50vw;
  min-height: 20vh;
  text-align: center;

  &:hover {
    background: #4cb16b;
  }

  @media (min-width: 768px) {
    width: 20vw;
  }

  svg {
    color: #00722e;
    margin-bottom: 20px;
  }
`;

const Home: React.FC = () => {
  return (
    
      
        
          
             Item 1
          
        
        
           Item 2
        
        
           Item 3
        
        
           Item 4
        
      
    
  );
};

export default Home;

How to fix this error in NextJS 13?

P粉401901266P粉401901266465 days ago840

reply all(1)I'll reply

  • P粉129275658

    P粉1292756582023-09-20 15:06:12

    The problem is caused by the components of Next.js. I fixed it by replacing the component with a standard <a> tag:

    <a href="/stock">
      <ListItem>
        <Icon1 size={70} />
        项目1
      </ListItem>
    </a>

    This will force a full page refresh when the link is clicked, instead of enabling client-side navigation like this component. Please note that this is a workaround and may impact performance due to page reloads.

    reply
    0
  • Cancelreply