Next.js Discord

Discord Forum

How to handle internal links using Next.js 14+ (App Router)?

Answered
African Slender-snouted Crocodil… posted this in #help-forum
Open in Discord
African Slender-snouted CrocodileOP
I have a CMS. In the CMS I have an article schema/type or whatever you want to call it.
In this schema I have a body field. In this body field I can write HTML markup. I want to be able to add links (anchor tags) in this markup.

In my React components I use <Link> from next/link.

How should I handle my internal links that I have in my CMS so that when a user clicks on a link the app does not do a full page refresh?
Answered by Roseate Spoonbill
Personally, I'd use something like https://www.npmjs.com/package/html-react-parser and replace all relative links (or links starting with app domain) with <Link> component. That's how I approach any html customization on application side, while still preserving the ability to edit html (e.g. in wisiwig editor) in cms.
View full answer

5 Replies

African Slender-snouted CrocodileOP
Hi, does anyone know how to handle this using Next.js?
Roseate Spoonbill
Personally, I'd use something like https://www.npmjs.com/package/html-react-parser and replace all relative links (or links starting with app domain) with <Link> component. That's how I approach any html customization on application side, while still preserving the ability to edit html (e.g. in wisiwig editor) in cms.
Answer
African Slender-snouted CrocodileOP
Interesting. So I would in my WYSIWYG add <a href=""> tags and then this library would convert the a-tags into <Link> tags?
Roseate Spoonbill
It wouldn't do it on its own - you have to write specific code, that detects the tag, and returns <Link> component instead. Take a look at the examples on npm page with replace option callback.
African Slender-snouted CrocodileOP
Thanks, I ended up using the html-react-parserlibrary with the help of AI 😉