Tutorials / ReactJS
Posted 5.27.2018
By Audrey Burk

A Component to Hijack <a> Tags in Your React App

Handle traditional links by capturing them with this simple component.

We’ve previously written about some of the complexity of rendering WordPress content in a React app, and how the upcoming Gutenberg release will assuage much of it. One issue we’ll still have to account for, though, is the presence of links in WordPress posts — links that innately break our single-page paradigm.

See, when we build out a React app, we use React Router and its <Link> component to handle site navigation. But when we render plain <a> tags from WordPress posts, React Router won’t be aware of them. By default, using one of these links will trigger a page reload; and beside the fact that it’s Bad Practice, unnecessary page reloading can destroy a good user experience.

One issue we’ll have to account for, though, is the presence of links in WordPress posts.

For example, the KQED.org site features two main points of interest: articles to read, and an audio player that provides access to the live stream and previously aired shows. Users enjoy browsing the site while catching up on their favorite radio programs. But without a bit of tweaking, the links in those articles would load the page anew — and the users would lose their audio.

So how do we prevent that? We use a component to wrap the user-written content and triage any clicks on <a> tags. Whenever a link is clicked, we look at the destination and determine whether it’s actually an external link, or if we should be handling it internally with React Router.

There’s a lot to account for when analyzing the links. Do they use the same protocol? Do they go to the same domain? To different subdomains? If so, are those subdomains just aliases, or different sites altogether? It’s a bit of a mess.

Happily, we got it all sorted out and published the component on NPM, so if you need to integrate CMS content into your React app, go ahead and check out the package and usage on Github. Use it to wrap your content, and you’re good to go!