Issue
I have an object which I want to send to a component and create <ul>
<li>
list like menu.
const Data = [
{
name: "Item 1",
children: []
},
{
name: "Item 2",
children: []
},
{
name: "Item 3",
show: false,
children: [
{
name: "Child Item 1",
children: []
},
{
name: "Child Item 2",
children: []
},
{
name: "Child Item 3",
show: false,
children: [
{
name: "Child Child Item 1",
children: []
}
]
}
]
}
];
Now i want to parse this data to a component and like to create a menu of list of n number without using any static value which should look like something like below html.
<ul>
<li>
<a>Item 1</a>
</li>
<li>
<a>Item 2</a>
</li>
<li>
<a>Item 3</a>
<ul>
<li>
<a>Child Item 1</a>
</li>
<li>
<a>Child Item 2</a>
</li>
<li>
<a>Child Item 3</a>
<ul>
<li>
<a>Child Child Item 1</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>;
I have done this using multiple map
functions but that will not work if I don't know the number of children's present.
Solution
You can create recursive component like this:
const TreeMenu = ({ data }) => {
if (!data.children) // If it has no children just return its name
return (
<li>
<a>{data.name}</a>
</li>
);
return (
<ul style={{ marginLeft: '1rem' }}>
<a>{data.name}</a>
{data.children.map((item) => (
<TreeMenu data={item} />
))}
</ul>
);
};
I slightly modified the initial data to make the recursive function easier:
const Data = {
children: [
{
name: 'Item 1',
children: [],
},
{
name: 'Item 2',
children: [],
},
{
name: 'Item 3',
show: false,
children: [
{
name: 'Child Item 1',
children: [],
},
{
name: 'Child Item 2',
children: [],
},
{
name: 'Child Item 3',
show: false,
children: [
{
name: 'Child Child Item 1',
children: [],
},
],
},
],
},
],
};
Answered By - Alp Özaslan Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.