How to render React Component into itself, in a recursive way

You should abstract your rendering logic into a separate method, which you can call recursively from the "render" method:

import List from 'somewhere';

class RecursiveItems extends React.PureComponent {
  constructListItem = (item) => {
    if (item.nestedItems) {
      return (
        <List key={item.key}>
          {item.nestedItems.map(this.constructListItem)}
        </List>
      )
    } else {
      return <ListItem key={item.key} item={item} />
    }
  }

  render() {
    const { listItems } = this.props

    return (
      <List>
        {listItems.map(this.constructListItem)}
      </List>
    )
  }
}

export default RecursiveItems

Completely untested code but it should give the idea.


Using functional components:

//List.js
import React from 'react';

import ListItem from '../your_path/ListItem';

export default function List({items}) {
  return(
    <div className="list">
    {
      items.map(item => {
        if(item.name){
          return <ListItem item={item} />
        }
        return <List items={item} /> 
      })
    }
    </div>
  );
}


//ListItem.js: 
import React from 'react';
export default function ListItem({item}){
  return (
    <div className="list-item">Name: {item.name}</div>
  )
}

Didn't test, but I think this should work..