Skip to content
Advertisement

Next.js: Error: React.Children.only expected to receive a single React element child

I’m having a component called Nav inside components directory and it’s code is some thing like below:

import Link from 'next/link';

const Nav = () => {
    return(
        <div>
            <Link href="/">  <a> Home </a> </Link>
            <Link href="/about"> <a> About </a>  </Link>
        </div>
    )
}

export default Nav;

This gives me the error:

Error: React.Children.only expected to receive a single React element child.

But if I remove the <a> tags within <Link> components, I can view the pages, but then in the console I’m getting a warning of:

Warning: You're using a string directly inside <Link>. This usage has been deprecated. Please add an <a> tag as child of <Link>

So what am I doing wrong here?

Advertisement

Answer

This issue is due to the space between <Link> tag and <a> tag.

So change your code like,

        <div>
            <Link href="/"><a> Home </a></Link>
            <Link href="/about"><a> About </a></Link>
        </div>

Reason for the change:

-> The <Link> can have only one child node and here the space between the link and a tag are considered as a child nodes.

-> So there are two child nodes (One is space and another is <a> tag) which is invalid and hence such error occurs.

Advertisement