How to Recursively Render the React Component

Naveen DA
3 min readSep 14, 2020

--

How to Recursively Render the React Component

Quick Summary

I was implementing the employee-org-chart on my react project, so I need to render the component recursively. It was really fun and very easy in react. So I decided to create an article on it.

Introduction

In the programming world recursive play a big role, it will reduce the code and enable us to run again and again until the condition satisfied.

In React, render a component recursively is not a big deal it is actually a very simple one.

Data Structure

I am gonna use a general parent-child-… data structure

https://www.npmjs.com/package/react-organizational-chart

Alright let's build the app

Step 1: Init Project

Create the react app using the create-react-app by running this command

npx create-react-app react-recursively-tutorial
Simple Create Project

after running the project, so can see this screen on your browser

Step 2: Basic File

Create a file called employee-chart.js and a very simple react component

import * as React from "react";const EmployeeChart = props => {
return <div>Hello Chart</div>;
};
export default EmployeeChart;

Step 3: Render the component Recursively

Let us create a component inside the employee-chart.js called card

const Card = props => {
return
(
<>
{props.data.map(item =>(
<div className="card">
{item.name}
</div>
))}
</>
)
};

If you pass our data to the component, it will render only one time, but need to render the component if it has childern properties

const Card = props => {

return(
<>
{props.data.map(item =>(
<div className="card">
{item.name}
{item.children?.length && <Card data={item.children} />}
</div>
))}
</>
)
};
React Recursively Rendered Component

Here we are passing the same component with one if-checks, it will allow us to render the component Recursively.

Step 4: Final Code

Just simply pass the data to Card component, it will render recursively

import * as React from "react";
import data from "./data.json";
const Card = (props) => {
return (
<>
{props.data.map((item) => (
<>
<div className="card">
{item.name}
{item.children?.length && <Card data={item.children} />}
</div>
</>
))}
</>
);
};
const EmployeeChart = (props) => {
return (
<div>
Employee Chart
<Card data={data} />
</div>
);
};
export default EmployeeChart;

Final Output

Simple React Recursively Rendered Component Demo

It is not a fancy output, but it rendered recursively.

Thanks for sticking until the end :)

P.S. 👋 Hi, I’m Naveen DA! If you liked this, consider following me on twitter and sharing the story with your developer friends 🐋😀

--

--

Naveen DA
Naveen DA

Responses (1)