Sometimes your list may have a sublist inside it which again may have another sublist in it.
In that case simple loop won't work. You have to use recursion.
So let's see how we can render recursive list using React JS.
Since react supports JSX and we can use regular JavaScript functions so we can simply use a recursive function.
//App.js
function App(){
const list = [
{ type: "item", title: "Wakeup", color: "blue" },
{ type: "item", title: "Get Fresh", color: "blue" },
{ type: "item", title: "Study", color: "blue" },
{
type: "list",
items: [
{ type: "item", title: "Study JavaScript", color: "green" },
{ type: "item", title: "Study OOP", color: "green" },
{
type: "list",
items: [
{ type: "item", title: "Make game using OOP", color: "red" }
]
},
{ type: "item", title: "Study NodeJs", color: "green" },
]
}
]
function renderList(list){
const listTree = list.map(item => {
if(item.type == "item"){
return (
<div className="list-item">
<span className="border" style={{background: item.color}}></span>
<span className="title">{ item.title }</span>
</div>
)
}else{
return (
<div className="list">
{ renderList(item.items) }
</div>
)
}
})
return (
<div className="list">
{ listTree }
</div>
)
}
return (
<div>
<h1>My Nested ToDo List-</h1>
{ renderList(list) }
</div>
)
}
export default App
Now depending on how you style it in CSS it should look something like this.
Now let's see how to render recursive list in Vue JS.
Now we can't use recursive JavaScript function in Vue like we did in react but We can use recursive component.
To be able to use component recursively it must have a name properly!!!
App.vue
<template>
<div>
<h1>My Nested ToDo List-</h1>
<RenderList :list="list" />
</div>
</template>
<script>
import RenderList from "./components/RenderList.vue"
export default {
components: {
RenderList
},
data: () => ({
list: [
{ type: "item", title: "Wakeup", color: "blue" },
{ type: "item", title: "Get Fresh", color: "blue" },
{ type: "item", title: "Study", color: "blue" },
{
type: "list",
items: [
{ type: "item", title: "Study JavaScript", color: "green" },
{ type: "item", title: "Study OOP", color: "green" },
{
type: "list",
items: [
{ type: "item", title: "Make game using OOP", color: "red" }
]
},
{ type: "item", title: "Study NodeJs", color: "green" },
]
}
]
})
}
</script>
RenderList.vue
<template>
<div class="list">
<div v-for="item in list" :key="item.title" :class="{'list': item.type == 'list', 'list-item': item.type == 'item'}">
<span v-if="item.type == 'item'" class="border" :style="{background: item.color}"></span>
<span v-if="item.type == 'item'" class="title">{{ item.title }}</span>
<RenderList v-if="item.type == 'list'" :list="item.items" />
</div>
</div>
</template>
<script>
export default {
name: "RenderList",
props: ['list']
}
</script>
Again depending on how you style it in CSS it should look something like this.
Make sure to check out my other articles and YouTube channel.
Top comments (0)