Author avatar

Gaurav Singhal

How to Render <a> with Optional href in React

Gaurav Singhal

  • Nov 12, 2020
  • 7 Min read
  • Nov 12, 2020
  • 7 Min read
Web Development
Front End Web Development
Client-side Framework


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 <a> 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.

2    name: '',
3    email:'',
4    sector:'',
5    linkedinHandle:'',
6    ...

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:

1<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:

1npx 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:

1import React from 'react';
4function App() {
5  return (
6    <div className="App">
8    </div>
9  );
12export 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.

1import React,{useState} from 'react';
4function App() {
5  const [state,setState]=useState(false);
6  let url="";
7  return (
8    <div className="App">
9     <a href={url}>LinkedIn handle</a>
10    </div>
11  );
14export 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.

1  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.

1import React,{useState} from 'react';
4function App() {
5  const [state,setState]=useState(false);
6  let url="";
7  let element=<p>No handle exists for this user!</p>;
8  if(state) element=<a href={url}>LinkedIn handle</a>;
9  return(
10    <div className="App">
11     {element}
12    </div>
13  );
16export default App;

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

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

Using the Ternary Operator

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

2let element= state? <a href={url}>LinkedIn handle</a>
3                  : <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.

1import React,{useState} from 'react';
4function App() {
5  const [state,setState]=useState(false);
6  let url="";
7  let element=<a href={url}>LinkedIn handle</a>;
8  return(
9    <div className="App">
10     {state && element}
11    </div>
12  );
15export 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.


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.