DEV Community

roggc
roggc

Posted on

Calling a component recursively in React.js

This post was made after reading this, which talks about the same thing (in Vue.js).
The call to a component recursively must be driven by recursive data, which will define the tree of nested calls that will be made.
Let's say we have this recursive (nested) data:

  const recursive={
    arr:[
      {
        arr:[
          {
            arr:[],
            val:'a'
          },
          {
            arr:[],
            val:'b'
          },
        ],
        val:'c'
      },
      {
        arr:[],
        val:'d'
      }
    ],
    val:'e'
  }
Enter fullscreen mode Exit fullscreen mode

We can use it to call a component recursively.
Let's define our recursive component:

import React,{useReducer} from 'react'
import s from 'styled-components'

export const Test1=({recursive})=>{
  const Div=s.div`
  `
  return (
    <Div>
    {recursive.val}
    {recursive.arr.map((it,i)=><Test1 key={i} recursive={it}/>)}
    </Div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Now let's define our App component which will call this recursive component for the first time:

import React from 'react'
import s from 'styled-components'
import {Test1} from '../test1/test1'

export const App=()=>{
  const Div=s.div`
  font-family:sans-serif;
  `
  const recursive={
    arr:[
      {
        arr:[
          {
            arr:[],
            val:'a'
          },
          {
            arr:[],
            val:'b'
          },
        ],
        val:'c'
      },
      {
        arr:[],
        val:'d'
      }
    ],
    val:'e'
  }

  return (
    <Div>
    <Test1 recursive={recursive}/>
    </Div>
  )
}
Enter fullscreen mode Exit fullscreen mode

The output for this in the browser will be:
Alt Text

Top comments (0)