I am currently working on implementing NextJs's <Link />
tag to wrap a NextJs <Image />
within my application in order to iterate over an array of data. Everything functions as expected and renders correctly when I place the <Link />
in a top-level page component. However, when I attempt to abstract this into a sub-component and then include the sub-component in the page component, I encounter errors indicating that
Error: Multiple children were passed to <Link> with
hrefof
/test, but only one child is supported https://nextjs.org/docs/messages/link-multiple-children
unless I remove all line breaks from the source code.
For instance, the following setup works:
// pages/index.js
import Link from 'next/link';
import Image from 'next/image';
export default function Home({links}) {
return (
<>
<div id="container">
<main>
{links.map(link => {
return <Link key={link.link} href={link.link}>
<a><Image src={link.imageUrl} width={400} height={400}/></a>
</Link>;
})
}
</main>
</div>
</>
);
}
export async function getStaticProps() {
const response = await fetch('http://localhost:3000/api/links');
const links = await response.json();
return {
props: {
links
},
}
}
This also proves to be effective:
// pages/index.js
import Links from '../components/Links';
export default function Home({links}) {
return (
<>
<div id="container">
<main>
<Links links={links}/>
</main>
</div>
</>
);
}
export async function getStaticProps() {
const response = await fetch('http://localhost:3000/api/links');
const links = await response.json();
return {
props: {
links
},
}
}
// components/Links.js
import Image from 'next/image';
import Link from 'next/link';
export default function Links({links}) {
return links.map(link => {
return <Link key={link.link} href={link.link}><a><Image src={link.imageUrl} width={400} height={400}/></a></Link>;
},
);
}
However, the following setup fails:
// pages/index.js
import Links from '../components/Links';
export default function Home({links}) {
return (
<>
<div id="container">
<main>
<Links links={links}/>
</main>
</div>
</>
);
}
export async function getStaticProps() {
const response = await fetch('http://localhost:3000/api/links');
const links = await response.json();
return {
props: {
links
},
}
}
// components/Links.js
import Image from 'next/image';
import Link from 'next/link';
export default function Links({links}) {
return links.map(link => {
return <Link key={link.link} href={link.link}>
<a>
<Image src={link.imageUrl} width={400} height={400}/>
</a>
</Link>;
},
);
}
All assistance is greatly appreciated!