Create a breadcrumb list of links with JavaScript and use it inside your React applications!

The advantages of using breadcrumbs in your web applications are widely known.

  • The users get a chain of links that helps them understand where they are in your website and how they came to this page, and how provides them an easy when to navigate back in the hierarchy of links.

  • Breadcrumbs are considered to be a best practice for the SEO of your application.

Suppose we have the following example of chained links in a breadcrumb:

Main page > Main category 1 > Sub category 1 > Product 1

First, lets see how you have to implement the links in the breadcrumb of each page that navigate to the next sub-page. For this we use the JSX element <Link> of React.

The root level of the application will have links to various main categories. Here is an example of a link which navigates to the “main category 1” page:

<Link to="/main-category-1/">Main category 1</Link>

In the “main category 1” page we define the following link that navigates the user to the “sub category 1” page:

<Link to="/main-category-1/sub-category-1/">Sub category 1</Link>

In the “sub category 1” page we define the following link that navigates the user to the “product 1” page:

<Link to="/main-category-1/sub-category-1/product-1/">Sub category 1</Link>

In the “product 1” page we reached the end of the breadcrumb, so there is no link there.

We now want to implement in each page the breadcrumb structure of the current page by writing code in JavaScript. In the previous example we had a small structure of links; imagine though what would happen if we had to show 5 or 10 or 20 links in one breadcrumb. For this reason we want to make our code implementation to be adaptable to the current chain of links. The location object of the window object comes into the rescue.

Following is the code which creates the breadcrumb link structure for our React application. I tried to comment the code so good as possible, so that you understand why we make each step.

  • The initial step to extract the pathname out of the URL by using the window.location.pathname JavaScript property.

  • We split the pathname based on the / character and we normalize the parts of the pathname, by removing the first or the last element of the array if needed.

  • We use the map function for arrays to apply logic for each element of the pathname-array.

  • We attach the > symbol only between two links and not at the end of the breadcrumb.

  • The first element in the array is the homepage of our application. The root url needs to be constructed with the help of the <IndexLink> element, which is specifically being used from React for creating a link that navigates to the root of the application. The activeClassName is the name of the class that you define for the root link.

  • We calculate the link of the current path, by starting from the root element and going till the current element.

  • For all the links except the first one we use the <Link> element.

  • We use the standard render() function of React to attach our breadcrumb into the JSX code of our component when this component gets rendered.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    generateBreadCrumb(pathname) {
        var paths = pathname.split("/");
        
        // remove the last element if there was a / at the end of the pathname
        paths = paths[paths.length-1] === "" ? paths.slice(0, paths.length-1): paths;
        
        // remove the first element if the second one is an empty string which means that we are in the root of the website
        paths = paths[1] === "" ? paths.slice(1) : paths;
        
        var breadcrumb = paths.map((path, index) => {
            // Add the > symbol only between two links
            var arrow = index !== paths.length-1 ? " > " : " ";
            
            // The first element should receive the <IndexLink> React element
            if (index === 0) {
                return (<li><IndexLink key={index} to="/" activeClassName="active">Home</IndexLink>{arrow}</li>);
            }
            
            // Build the path for the current URL
            var url = '/' + paths.slice(0, index+1).join('/');
            
            // HTML structure for every link except the first
            return (<li><Link key={index} to={url}>{path}</Link>{arrow}</li>);
        });
        
        // Return a list of links
        return (<ul className="inline-list">{breadcrumb}</ul>);
    }
    
    
    render() {
        // When rendering the component, calculate the HTML structure of the breadcrumb
        var breadcrumb = this.generateBreadCrumb(window.location.pathname);
        
        return (
            <div>
                {breadcrumb}
                // other JSX code
            </div>
        );
    }

The previous code will work also with “border” values of the pathname property:

  • ”/”

  • “/test1/test2/test3/”

  • “/test1/test2/test3/test4?prop1=1234&prop2=5678”

As an extention, you can define the breadcrumb as an own React component and use it in multiple pages and with other components. This way you impove the re-usability and modularization of your application.

That’s it. I hope that this quick guide helped you create a breadcrumb element in your React application or that you just saw how to make breadcrumb, after all its all plain JavaScript.

comments powered by Disqus