DEV Community

Cover image for AutoLink: Simplifying Conditional Navigation in React Router Projects
Andreas Riedmüller
Andreas Riedmüller

Posted on

AutoLink: Simplifying Conditional Navigation in React Router Projects

In React applications, conditional rendering often leads to verbose and repetitive code. For this reason I've created a component called AutoLink to handle the decision between using a traditional <a> tag for external links and React Router's <Link> for internal navigation.

Here is my TypeScript implementation for this component:

import React from "react";
import { Link, LinkProps } from "react-router-dom";

type AutoLinkProps =
  | (React.HTMLProps<HTMLAnchorElement> & { to: undefined })
  | LinkProps;

export function AutoLink(props: AutoLinkProps) {
  const to = props.to;
  if (typeof to !== "undefined") {
    return <Link {...props} />;
  } else {
    // eslint-disable-next-line jsx-a11y/anchor-has-content
    return <a {...props} />;
  }
}
Enter fullscreen mode Exit fullscreen mode

Here's a quick breakdown of what AutoLink does:

  • Unified Interface: It provides a single interface for both external and internal links.
  • Conditional Rendering: Internally, it checks if the to prop is defined. If so, it renders React Router's <Link>; otherwise, it falls back to a standard <a> tag.
  • Type Safety: The component uses TypeScript for props definition, ensuring that either standard anchor attributes or React Router's LinkProps are correctly passed.

How to Use AutoLink

Simply import AutoLink and use it like you would a regular <a> or <Link>. Provide the to prop for internal navigation managed by React Router, or omit it for external links:

import React from "react";
import AutoLink from "..components/AutoLink";

const NavigationExample = () => (
  <div>
    <AutoLink to="/internal-page">Internal Page</AutoLink>
    <AutoLink href="https://external.site">External Site</AutoLink>
  </div>
);

export default NavigationExample;
Enter fullscreen mode Exit fullscreen mode

I have been using the AutoLink component for some time in several projects and find it particularly useful, I hope it helps you too!

Top comments (0)