2

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

Laurenz1606
  • 88
  • 13

3 Answers3

2

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

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
1

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.

lvilasboas
  • 76
  • 1
  • 6
  • Thanks for your replie, but my problem with a negativ margin is, that the container changes its height on other devices for responsiveness. Is it a huge problem, if i leave it so? – Laurenz1606 Mar 21 '21 at 18:26
0

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

Bart Krakowski
  • 1,655
  • 2
  • 8
  • 25