Laurenz1606
Laurenz1606

Reputation: 98

react-router-dom(ReactJS) nesting <Link /> components

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 :)

Upvotes: 2

Views: 2347

Answers (3)

Ajeet Shah
Ajeet Shah

Reputation: 19813

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:

enter image description here

Upvotes: 2

Bart Krakowski
Bart Krakowski

Reputation: 1670

Yeah, that's correct behavior, because the browser cannot render a nested attributes. You need to nest Links in the Route component. Here is a working example: https://reactrouter.com/web/example/nesting

Upvotes: 0

lvilasboas
lvilasboas

Reputation: 76

You said that the compiler gives you the mentioned error, but it is not an error, it clearly states it is a Warning.

One way to get around this would be to move the nested Link out of the parent Link, and via CSS (using maybe a negative margin, or absolute positioning), you visually move the then-nested Link onto the then-parent Link.

This way, semantically you are doing things the right way, while still achieving what you visually wanted.

Upvotes: 1

Related Questions