Hello React developers,
I've been working on a multi-site react projet, but now i've ran in small issue, which im not know how to fix. My Problem is Following:
I've got a component which looks like:
import React from 'react'
import { Link } from 'react-router-dom'
export default function MyComponent({tag, Text, id}) {
return (
<Link to={"/article/" + id}>
<div>
<p>{Text}</p>
<Link to={"/tags/" + tag.text}>{tag.text}</Link>
</div>
</Link>
)
}
Error: index.js:1 Warning: validateDOMNesting(...): <a> cannot appear as a descendant of <a>.
Everything is working as it should, i've get a container with the text and the tag, when i click on the container it redirects me to /article/[ARTICLE_ID] and when i click on its tag, it redirects me to /tag/[TAG_ID], the only problem is, that the react compiler gives me an error in the console saying, that you can not put a Link in a Link, but it compiles and works. Is there any way to get around this error, or can i ignore it(what i wouldn't like)?
ps: my english is not the best i know, but i will work on it :)
You are seeing the warning..
<a>
cannot appear as a descendant of<a>
.. as an anchor tag (rendered by Link
here) inside another one is not a valid HTML. See this related post.
To fix it, you can use Link
i.e. anchor tag and a button
and make the button look like a link using CSS, (e.g. if using bootstrap - "btn btn-link" classes):
And use preventDefault
and stopPropagation
on the button click:
<Link to="/page1">
<div>
<p>Page1</p>
<button
className="btn btn-link px-0"
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
history.push('/page2')
}}
>
Page2
</button>
</div>
</Link>
Snapshot of output: