DEV Community

roggc
roggc

Posted on

4 1

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay