Author avatar

Gaurav Singhal

How to Render <a> with Optional href in React

Gaurav Singhal

  • May 18, 2020
  • 7 Min read
  • 4,511 Views
  • May 18, 2020
  • 7 Min read
  • 4,511 Views
Web Development
Front End Web Development
Client-side Framework
React

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

The anchor tag in JSX navigates to different web pages through the href attribute. However, to navigate to different sections of your app, the React alternative for <a> is < link>, and in-app navigation should always be handed over to < link>. Use <a> only when you want to navigate to an external source or a page outside of your app. 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.

1
2
3
4
5
6
7
user={
    name: '',
    email:'',
    sector:'',
    linkedinHandle:'',
    ...
}
javascript

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>
jsx

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:

1
npx create-react-app optional-href-rendering
shell

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:

1
2
3
4
5
6
7
8
9
10
11
12
import React from 'react';


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

export default App;
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
jsx

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>;
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
jsx

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

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

Using the Ternary Operator

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

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

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
jsx

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.

0