Comparing React tree components

From note-taking apps to complex data structures, trees diagrams are everywhere around us. They help in the arrangement of data, thus allowing users to navigate their items easily. One notable example of tree usage can be the CodeSandbox editor:

CodeSandbox Tree Editor

In this article, you will learn how to render tree charts to the user interface in React. Furthermore, we’ll compare several libraries with basic code samples to help you determine the best fit for your web app.
We will cover the following libraries:

Geist UI

Geist UI offers a set of components that replicate Vercel’s design language. One of them is a File Tree component that renders a catalog of files and folders in a tree format.

To install the Geist UI library in your project, run the following terminal command:

npm i geist-ui/react

Basic usage of Geist UI

The following snippet renders a simple file tree:

import {Tree} from "@geist-ui/react"
return (
  <div>
    <Tree>
      <Tree.Folder name="src">
        <Tree.File name="app.js" />
        <Tree.File name="index.js" />
        <Tree.Folder name="Components">
          <Tree.File name="Layout.js" />
        </Tree.Folder>
      </Tree.Folder>
      <Tree.File name="package.json" />
    </Tree>
  </div>
);

Here, the Tree module denotes the start of a tree view. The Tree.Folder and Tree.File components represent folders and files respectively.

Geist UI Basic Tree

Geist even allows developers to append event handlers to the tree view. This is handy for situations where your app needs to execute some code if the client clicks on a particular element. One such example might be to open a new window or fetch data if the user clicks on a specific file name:

const eventHandler = (path) => {
    console.log(path); //output the clicked file's path
  };
  return (
    <div>
      <Tree onClick={eventHandler}>
      </Tree>
    </div>
  );

In this code, we passed in our eventHandler function to the onClick prop. This means that whenever the user clicks on a certain file, React will execute the eventHandler method.

Geist UI with the eventHandler Method

Advantages

  • The easiest solution to display a file structure. Geist UI requires no boilerplate code to help you get started
  • Has support for dark and light themes

Disadvantages

  • Lacks customization options (for example, custom icons and colors)
  • As the name of this module suggests, it won’t let you build complex tree structures (for example, a family tree). To mitigate this issue, we will use the React D3 Tree package later on

Ant Design

Ant Design is one of the most well-known React UI technologies. This is because it is easy to use and lets developers build rich and interactive interfaces with minimal amounts of code. In fact, large corporations like Alibaba use it in their applications.

Just like Geist, Ant Design offers a tree component to represent hierarchical structures.

To use Ant Design’s features, install the antd dependency into your project like so:

npm install antd 

Sample usage for Ant Design

Before rendering a tree, we need to define our data source first:

const treeData = [
  {
    title: "Main file structure",
    key: "MainStructure",
    children: [
      {
        title: "Layouts",
        key: "layoutFolder",
        children: [ //child element
          {
            title: "MainLayout.js",
            key: "mainlayout.js"
          }
        ]
      },
      { title: "index.js", key: "index.js" }
    ]
  }
];

Here, each item in this array needs to have a title and key property. The children array tells Ant Design to render child elements under its respective subgroup.

As the second step, pass in this treeData array into the Tree component like so:

import "antd/dist/antd.css";
import { Tree } from "antd";

return <Tree treeData={treeData} />; 

In this code, we passed in our data into the treeData prop. This will display a tree component with our chosen data.

Ant Design Basic Tree

Ant Design also allows for customization. For example, to get checkboxes, use the checkable prop:

return <Tree checkable treeData={treeData} />;

Ant Design Checkable Prop

Advantages

  • Unlike Geist, Ant Design offers an extensive API to extend your tree’s functionality
  • Simple to use
  • Allows for customization to some extent, for example, custom icons or draggable lists
  • Capable of loading data asynchronously. This means that Ant Design can let users populate their tree via an API as a data source
  • Has great documentation with loads of code recipes

Disadvantages

  • Just like Geist UI, it does not allow for the building of complex tree diagrams (like binary trees)
  • Since it is a full-fledged component set, it has a large bundle size. If your app targets devices with minimal resources, avoid this library. To circumvent this problem, you can use the rc-tree component. Its usage is similar to that of Ant Design’s tree module

Fluent UI

Fluent UI is Microsoft’s component library that stems from the tech giant’s Fluent Design System. It will be used in upcoming Office products.
Just like all major component utilities, it also lets developers render simple tree diagrams via the tree element.

To install the Fluent UI React package, execute this bash command:

npm i @fluentui/react-northstar

Sample usage for Fluent UI

As the first step, define your data source like so:

const items = [
  {
    id: "concepts",
    title: "Top concepts to learn"
  },
  {
    id: "top-tech",
    title: "Top technologies to learn",
    items: [{ id: "react", title: "React" }] //this item will have children
  },
  {
    id: "best-accessories",
    title: "Best iPad accessories",
    items: [
      {
        id: "screen-protector",
        title: "Screen protectors",
        //child items of this sub group:
        items: [{ id: "paperlike", title: "Paperlike protector" }] 
      }
    ]
  }
];

Each element in the items array denotes a node in the tree. If an object includes an items property, this will tell Fluent UI to render a child node.

Next, pass in this data into the Tree component like so:

import { Provider, teamsTheme, Tree } from "@fluentui/react-northstar";

export default function FluentTreeComponent() {
  return (
    <Provider theme={teamsTheme}>
      <Tree items={items} aria-label="tree" />
    </Provider>
  );
}

Here, we have passed in the items array. This will render a tree based on our data source.

Fluent UI Basic Tree

We can even enable checkbox support via the selectable prop:

<Tree items={items} selectable aria-label="tree" />

Fluent UI Selectable Prop Tree

Advantages

  • Like Ant Design, it has an extensive API to expand the tree’s functionality
  • Fluent UI allows developers to change the look and feel of their nodes. For example, a custom title renderer

Disadvantages

  • Just like Ant Design or Geist UI, if you are looking to build complex trees, steer clear from this library
  • Large bundle size, thus bloating up your project and causing performance issues

React D3 Tree

React D3 Tree is a React component that offers a way of building complex tree types; for example, family trees and binary trees.

To use this module, install the react-d3-tree package with this command:

npm install react-d3-tree

Sample usage for React D3 Tree

First, define your data structure:

const technologies = {
  name: "JavaScript",
  children: [
    {
      name: "React"
    },
    {
      name: "Node.js",
      children: [{ name: "Express" }, { name: "Http" }] //children of this element
    }
  ]
};

Each object in the array has to have a name element. The children property will render a child node.

Next, pass in your technologies array into the component:

return (
  <div id="treeWrapper" style={{ width: "100vh", height: "100vh" }}>
    <Tree
      data={technologies}
    />
  </div>
);

React D3 Tree Sample Usage

Creating a binary tree with React D3 Tree

React D3 Tree is commonly used to build binary trees. As a demonstration, let’s recreate this tree diagram from Wikipedia:

Wikipedia Binary Tree Example

This will be the corresponding data structure of the above diagram:

const binaryData = {
  name: 2, //root node
  children: [
    {
      name: 7,
      //children of the '7' node.
      children: [
        { name: 2 },
        { name: 6, children: [{ name: 5 }, { name: 11 }] }
      ]
    },
    { name: 5, children: [{ name: 9, children: [{ name: 4 }] }] }
  ]
};
<Tree
  data={binaryData}
  orientation="vertical"
  pathFunc="straight"
  nodeSize={{ x: 100, y: 100 }}
/>;

Here, the orientation prop changes the orientation of our chart to vertical. We also used the pathFunc property, which alters the look of the lines that connect each node. Furthermore, nodeSize controls the distance between each node.

React D3 Binary Tree

Advantages

  • Has an API that allows developers to extend their charts’ features
  • Great for building complicated trees types (for example, binary trees, family trees, and organizational charts)
  • Lets developers customize the look and feel of their tree diagram

Disadvantages

  • No support for radial trees. This means that your UI might look cluttered if many child nodes are on the screen

Which React tree component should you use?

If your app needs to render simple tree diagrams and you want customization options, use Ant Design. The documentation is well-explained and offers many code recipes. Other than that, the library is also a breeze to work with.

However, if you want to display complicated tree charts (for example, decision trees or traverse trees), look no further than React D3 Tree. On top of being straightforward, it also has a smaller footprint, which results in low performance costs.

Conclusion

In this article, we explored a handful of libraries to render trees diagrams in React. At this moment, I would opt for using Ant Design in my projects. Not only is it easy to use, but it’s also robust. Consequently, this brings app security and efficiency to the table.

Thank you so much for reading! Happy coding!

The source code for this article is located in this CodeSandbox project.

The post Comparing React tree components appeared first on LogRocket Blog.

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Comparing React tree components

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.