Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Created June 25, 2019 03:27
Show Gist options
  • Select an option

  • Save anushshukla/b8c25f584af6487b46a04105efdf3ba6 to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/b8c25f584af6487b46a04105efdf3ba6 to your computer and use it in GitHub Desktop.
Nested Category Listing Sample in React
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
ul {
list-style-type: none;
}
</style>
</head>
<body>
<div id="root"></div>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
const mixedNestedCategories = [
{ id: 1 },
{ id: 5 },
{ id: 2, pid: 1 },
{ id: 3, pid: 1 },
{ id: 4, pid: 2 },
{ id: 6, pid: 1 },
{ id: 7, pid: 5 }
];
const Task = props => {
const [state, setState] = React.useState({ categories: [], subCategories: {} });
const onMount = () => {
const subCategories = {};
const categories = [];
const mapCallback = row => {
if (!row.pid) {
categories.push(row);
} else {
if (!subCategories[row.pid]) subCategories[row.pid] = [];
subCategories[row.pid].push(row);
}
}
props.mixedNestedCategories.map(mapCallback);
setState({ categories, subCategories });
}
React.useEffect(onMount, [])
const renderList = row => {
const subCategories = state.subCategories[row.id];
if (subCategories) {
return (
<li key={row.id}>
> {row.id}
<ul>
{subCategories.map(renderList)}
</ul>
</li>
);
}
return (
<li key={row.id}>
> {row.id}
</li>
);
}
return (
<div>
<h1>Display Categories</h1>
<ul>
{state.categories.map(renderList)}
</ul>
</div>
);
}
ReactDOM.render(<Task mixedNestedCategories={mixedNestedCategories} />, document.getElementById('root'));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment