Render HTML tree from flat array structure

Balram Singh
2 min readSep 6, 2018

--

First step is to convert flat array into Hierarchy

const hierarchy = products.reduceRight((child, obj) => {
if (child) {
return [Object.assign({}, obj, { child })];
}
return [obj];
}, null);

This will return

const renderHierarchy = child => child.map(hierarchy => (
<Node node={hierarchy}>
{hierarchy.child}
</Node>
));

Node.jsx

import React from ‘react’;
import PropTypes from ‘prop-types’;
const propTypes = {
children: PropTypes.array,
node: PropTypes.object,
};
const defaultProps = {
children: null,
node: <div />,
};
export default function Node({ children, node }) {
let childnodes = null;
// the Node component calls itself if there are children
if (children) {
childnodes = children.map(childnode => (
<Node node={childnode} >
{childnode.child}
</Node>
));
}
// return our list element
// display children if there are any
return (
<li key={node.id}>
<span>{node.name}</span>
{ childnodes ?
<ul>{childnodes}</ul>
: null }
</li>
);
}
Node.propTypes = propTypes;
Node.defaultProps = defaultProps;

Test your output

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Balram Singh
Balram Singh

Written by Balram Singh

Organiser of React Scotland Meetup

No responses yet

Write a response