Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Render <a> with Optional href in React

Nov 12, 2020 • 8 Minute Read

Introduction

When you're developing an app to cater to all types of end users, conditional rendering allows you to automate your code to handle all predefined and dynamic cases without hardcoding solutions. Apart from keeping the code clean, short, and readable, it also manages a large number of possibilities with some simple structural logic.

In this guide, you'll learn how to render an anchor element in your React app with optional href based on specific conditions.

Overview of the Tag

The anchor tag in HTML is used to navigate to different web pages using an href attribute. This href attribute contains the URL or path to the destination page. It may be a relative URL or an absolute URL. In React, relative URLs should always be handled by the link tag provided by the React Router, and pure anchor tags should only be used for absolute paths. You can also think of relative URLs as in-app navigation, for example navigating to a particular route of the app and absolute paths as external links. The prevailing logic behind rendering optional href can be conveniently extended to the < link> as well, and in fact, any other JSX element or component.

Optional Rendering: Use Case and Solution

Consider a simple use case where you are maintaining a database of all the people who have applied for jobs through your app. On the frontend, you get the data that you want to output in the following format.

user={
    name: '',
    email:'',
    sector:'',
    linkedinHandle:'',
    ...
}

Your form asked users to enter their LinkedIn handles, but it wasn't a mandatory field, so there's a strong possibility that some people left it blank. While outputting the data, you do something like this:

<a href={user.linkedninHandle}></a>

If the backend returned an empty string, your href would be rendered as an empty string too, but that's not an optimal solution. If linkedinHandle doesn't exist for a user, the <a> shouldn't be visible at all, but the empty link is still clickable even though it points nowhere. Additionally, this could throw errors in cases when the property is returned as null or undefined. The accurate solution is using conditional rendering on the <a> itself so either it is rendered along with the appropriate link or the other JSX element is rendered.

Creating a New Project

Make sure you have Nodejs and npm installed in your machine (at least version 8 or higher) along with a code editor and a web browser (preferably Chrome or Firefox).

Create a new project using create-react-application:

npx create-react-app optional-href-rendering

Cleaning up the Template

Ideally, you could have a separate component handling this kind of logic in your app, but for brevity, let's put all the code inside App.js. Remove the logo, App.css, and all their imports from App.js. Clean out the starter template inside the App component. Your App.js should look like this:

import React from 'react';


function App() {
  return (
    <div className="App">
      
    </div>
  );
}

export default App;

Setting State for Toggling Condition

The condition is usually based on the type of data you receive from the backend, but a good practice is to use a toggling state to understand the rendering more dynamically. Consider data received from the backend, and based on that, a toggling state is set to either true or false. If it's true, the href will be rendered, and if false, it will not be rendered.

import React,{useState} from 'react';


function App() {
  const [state,setState]=useState(false);
  let url="";
  return (
    <div className="App">
     <a href={url}>LinkedIn handle</a>
    </div>
  );
}

export default App;

This renders a simple <a> with an empty href, but it's still a clickable link. Let's add conditional rendering to it.

Optionally Rendering an Element

If the href attribute for the user exists, the state is set to true and the <a> tag is shown, otherwise a message is displayed. Wrap the message to be shown in a JSX element and assign that element to a variable that can be conditionally outputted.

  let element=<p>No handle exists for this user!</p>;

Using an If Statement

Before rendering anything, simply check if the state is true and assign <a> to that element, otherwise let the whole component render as it is.

import React,{useState} from 'react';


function App() {
  const [state,setState]=useState(false);
  let url="";
  let element=<p>No handle exists for this user!</p>;
  if(state) element=<a href={url}>LinkedIn handle</a>;
  return(
    <div className="App">
     {element}
    </div>
  );
}

export default App;

Since the state is initially false, the message is displayed. Setting it to true will render the link as it is.

 ...
     const [state,setState]=useState(true);
 ...

Using the Ternary Operator

The same check can be performed using a ternary operator to keep the code more readable.

...
let element= state? <a href={url}>LinkedIn handle</a>
                  : <p>No handle exists for this user!</p>;
...

Using the && Operator

In case you don't want to display an element at all for the false state value, the && operator can be conveniently used.

import React,{useState} from 'react';


function App() {
  const [state,setState]=useState(false);
  let url="";
  let element=<a href={url}>LinkedIn handle</a>;
  return(
    <div className="App">
     {state && element}
    </div>
  );
}

export default App;


Since the state is evaluated first, the element is not rendered since it's false. Changing it to true renders the empty parent div.

Meeting the Needs of Your App

When implementing your solution to meet the need of your app, remember that toggling the state using setState should be done in a function performing the relevant check with the data received from the backend. The initial value of the state is arbitrarily chosen here, but you should initialize the state to a legal value depending on your code. If the evaluation of the condition is more dynamic in nature or it is not known beforehand, use relevant lifecycle hooks to ensure your code remains intact. Finally, it is not mandatory to use a state variable for evaluating your condition. In some cases, even a simple JavaScript variable will do, provided its scope is well defined and doesn't crash your code anywhere.

Conclusion

Optionally rendering an attribute is never an optimal solution to conditionally display content on your app. The emphasis should always be more on the element itself, as attributes do not affect its physical appearance entirely. Also, when conditionally rendering an element or even a component, all scenarios should be well thought through. Avoid rendering empty tags, elements, or strings and focus on giving feedback to the user by rendering something else in their place.

If you have any queries, feel free to reach out at Codealphabet.

Learn More