2

I'm trying to implement nested comments in React. Basically I got the code currently like this here.

The code looks like the following:

var nested = [...] function Comment({ comment }) { const nestedComments = comment.map(comment => { return <Comment comment={comment} />; }); console.log(nestedComments) return ( <div key={comment.id}> <span>{comment.body}</span> {nestedComments} </div> ); } ReactDOM.render( <Comment comment={nested}/>, document.getElementById('container') ); 

I'm getting an error like the following:

Uncaught TypeError: comment.map is not a function at Comment (eval at transform.run (VM70 browser.js:5811), <anonymous>:947:31) at VM134 react-dom.js:4767 at measureLifeCyclePerf (VM134 react-dom.js:4537) at ReactCompositeComponentWrapper._constructComponentWithoutOwner (VM134 react-dom.js:4766) at ReactCompositeComponentWrapper._constructComponent (VM134 react-dom.js:4741) at ReactCompositeComponentWrapper.mountComponent (VM134 react-dom.js:4649) at Object.mountComponent (VM134 react-dom.js:11551) at ReactDOMComponent.mountChildren (VM134 react-dom.js:10442) at ReactDOMComponent._createInitialChildren (VM134 react-dom.js:6176) at ReactDOMComponent.mountComponent (VM134 react-dom.js:5995) 

Not sure what I'm doing wrong here.

1
  • This check out this answer: this Commented Apr 25, 2019 at 15:39

1 Answer 1

1

I believe your structure is like

var nested= [ {comment_id: '..', comment_body: '..', comments: [{...}] }, ... ] 

In this case you should change you function to pass the comments array the second time and check whether the nested comments are present or not

Try

var nested = [...] function Comment({ comment }) { const nestedComments = null; if(typeof comment === 'array') nestedComments= comment.map(comment => { return <Comment comment={comment.comments} />; }); console.log(nestedComments) return ( <div key={comment.id}> <span>{comment.body}</span> {nestedComments} </div> ); } ReactDOM.render( <Comment comment={nested}/>, document.getElementById('container') ); 
Sign up to request clarification or add additional context in comments.

1 Comment

Using your code in his his jsfiddle seems not working.. jsfiddle.net/9afdkb4b

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.