'nextjs does not support an empty link - what is a workaround for this?
I want to use a <Link />
with no content inside of it within my app, but for whatever reason, if I don't pass any content to it I get the "multiple children" error - when in fact quite the opposite is occurring. [See the error here]
So, how would I get the following code to work without doing any funky workarounds? The documentation doesn't seem to mention anything about it.
<Link href="/example"></Link>
Just in case you're wondering why I'm doing this, when I'm processing clickable background-image
, instead of putting the link on the outside of the element with that property, I put it on the inside and make it take up the entire parent element - as opposed to breaking the structure of the page with an inline element (and potentially unnecessary extra HTML and CSS).
Thanks.
Solution 1:[1]
React Fragments can solve the problem; they don't add extra HTML elements. You could do something like this (make sure to import React):
<Link href="/example">
<React.Fragment></React.Fragment>
</Link>
Or simply:
<Link href="/example"><></></Link>
This way you're passing exactly "one child" to <Link>
that returns nothing.
Solution 2:[2]
You have to pass an anchor element as children and passHref
as prop of the Link
element.
<Link href="/example" passHref>
<a />
</Link>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | code |
Solution 2 | Artur Haddad |