DEV Community

Martin Lindgren
Martin Lindgren

Posted on

2

Recursive React component in Typescript

The titel says it all. A colluege wanted to know how to write a Recursive React component in Typescript. So i wrote a simple one with infinite depth.

import React, { useState } from "react";
type ItemType = {
id: Number;
title: String;
children: Array<Number>;
};
// Each "ItemType" element in the array have a array of children ID's. These refer
// to a ItemType.
// = This has a infinite depth.
const items: ItemType[] = [
{ id: 1, title: "Item 1", children: [2, 3, 4] },
{ id: 2, title: "Item 2", children: [1, 3, 4] },
{ id: 3, title: "Item 3", children: [1, 2, 4] },
{ id: 4, title: "Item 3", children: [1, 2, 3] }
];
function Item({ title, children }: ItemType): JSX.Element {
const [open, toggle] = useState(false);
// Given the children array with IDs, find each Item we refer to
const childElements = children.map(findChild) as ItemType[];
return (
<div>
<h6>
{title} children <button onClick={() => toggle(!open)}>Open</button>
</h6>
<ul>
{/* Loop children and run recursive */}
{open &&
childElements.map((child: ItemType) => (
<li>
<div>Child: {child.title}</div>
<Item {...child} />
</li>
))}
</ul>
</div>
);
}
function App() {
return (
<div>
{/* Start by iterating over all items */}
{items.map(item => (
<Item {...item} />
))}
</div>
);
}
// Function to find a Item by child id.
function findChild(childId: Number): ItemType | undefined {
return items.find(({ id }) => id === childId);
}
export default App;

Might be usefull for someone.

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay