This is happening inside of a Reddit clone I’ve created. If you use Reddit, you might recall that when you’re on a feed page, you can click a post to go to the post’s page. You can also click on the post author’s username, which then goes to that user’s profile page.
To achieve this, I’ve done the following. My code isn’t actually structured quite like this; I put the relevant components together to show what I’m talking about, and this is a massively condensed version of the real thing:
<NavLink to={`/posts/${post.id}`}>
<SinglePost>
<div>
<SinglePostAuthorBar>
<div>
<NavLink to={`/c/${community?.id}`}>c/{community?.name}</NavLink>
</div>
</SinglePostAuthorBar>
</div>
</SinglePost>
</NavLink>
As you can see, this leads to me having an a
tag nested inside of another a
tag.
Any suggestions on how I can do this so that I’m not breaking this rule or what-have-you? For example, is there a way I can link to the user’s profile page on a button click or something? At the moment, I’m not sure how else I can do this. I need the user to be able to click on the entire post to be linked to the post’s page, and I also need the user to be able to click on the author’s username to be linked to the author’s profile page.
Thanks!
Edit: The only other similar question I’ve found on here is this one, but the answer has a commenter saying that the answer is actually bad practice. However, the question contains an image that shows the structure of the thing that is essentially causing the problem I’ve run into as well.
2
Answers
You can emulate the click behavior of the nested link instead of using a native
<a>
tag. Obviously this is discouraged unless necessary (which it is in your case).tl;dr change the outer
<NavLink />
to a<div onClick={router.push(nextPage)} />
Some tips on reverse engineering sites like Reddit
In Reddit, the post is a
<div>
with anonClick
handler. You can verify this in Google Chrome / Chromium-based browsers as follows (as of 2023-07-21).in the JavaScript console and calling
temp1.click()
.<div />
withdata-testid="post-container"
(this is used for things like testing-library or Puppeteer). You can quickly jump to one of these with Ctrl-F in the Elements tab.<div />
which is the link, but we can go further and check out the "Event Listeners" tab, where we can remove all of the click handlers and verify that the<div />
is no longer responding to.click()
. We can even figure out which handler specifically is responsible for responding to.click()
.