How To Map An Array With Unknown Nesting Levels?
I have an array of comments which can have answers, so every element (comment) of the array can have nested elements (comments) and the nesting level is unknown, but I need to rend
Solution 1:
You would use a recursive function. Recursive means that the function calls itself, or in the case of React, a component that returns itself as a child.
Here is an example which renders the value as a paragraph element, and then renders the child comments.
functionComment(props) {
return (<><p>{props.value}</p>
{props.comments ?
props.comments.map(comment => {
return <Commentcomments={comment.comments} />
})
: null}
</>)
}
Solution 2:
You can render its recursively
const data = [
{
"value": "awesome",
"comments": [
{
"value": "thanks""comments": null
},
{
"value": "really awesome",
"comments": [
"value": "thanks again",
"comments": null
]
}
]
}
]
constCommentItem = (props) => {
return (
<div>{props.item.value}</div>
{
Array.isArrray(props.item.comments) &&
props.item.comments.length >= 1 &&
props.comments.map(comment => (
<CommentItemitem={comment.comments}/>
)
}
)
}
return data.map(comment =><CommentItemitem={comment}/>)
Post a Comment for "How To Map An Array With Unknown Nesting Levels?"