1

I've got a problem with my function, after calling it inside an if statement it works sometimes but it doesn't return the last return it starts again with new value.

Here's data I render:

 listData: [
    [
      {id: 1, title: 'list1'},
      {id: 2, title: 'list2'},
    ],
    {id: 3, title: 'list3'},
  ];

And function:

  isArray(a) {
    return (!!a) && (a.constructor === Array);
  }

  renderList(item, options) {
    if (this.isArray(item) === true) {
      item.map((child, childIndex) => {
        this.renderList(child, options)
      })
    }
    return (
      <List item={item} />
    )
  }
5
  • 2
    Use Array.isArray, or an actual polyfill, don't roll your own. Also, the recursive call is unnecessary, just return a div with the lists mapped inside it. Commented Jul 11, 2018 at 11:39
  • 1
    Your item.map() call doesn't have any effect. Even though the children might not be arrays and thus get returned, the result of the map() call is discarded. Commented Jul 11, 2018 at 11:39
  • @ChrisG what do you suggest? Commented Jul 11, 2018 at 11:44
  • @JaredSmith it will be more nested in the future Commented Jul 11, 2018 at 11:45
  • @Anna Have you tried the answer below? It works fine. Live code: codesandbox.io/s/6wnn5lxqp3 Commented Jul 11, 2018 at 11:48

2 Answers 2

3
renderList(item, options) {
    if ( Array.isArray(item) ) {
      return item.map( (child, childIndex) => {
        return this.renderList(child, options)
      })
    } else {
      return (
         <List item={item} />
      )
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is basically a duplicate of the answer below. The key point are the missing returns.
More likely yes, but I used Array.isArray instead of this.isArray
1

Please try this:

if (this.isArray(item) === true) {
  return item.map((child, childIndex) => {
    return this.renderList(child, options)
  })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.