Home > Back-end >  How to render an array of functions (all of them return divs) recursively?
How to render an array of functions (all of them return divs) recursively?

Time:10-25

I have a little problem with a recursion task that I found.

I have three functions that are stored in an array:

const One = () => <div>One</div>
const Two = () => <div>Two</div>
const Three = () => <div>Three</div>

const arr = [One, Two, Three]

Then I pass this array as a prop to another component in which I must write a recursive function to make One a parent of *Two, and Two a parent of Three.

The HTML shopuld look like that:

<div class='App-box'>
  One
  <div class='App-box'>
    Two
    <div class='App-box'>
      Three
    </div>
  </div>
</div>

I am able to write a recursive function for an array for objects or nested arrays but this one I cannot figure out.

CodePudding user response:

const data = {
  obj: One,
  children: [{
    obj: Two,
    children: [{
      obj: Three
    }]
  }]
}

export default App = () => {
  return (
    <RecursiveComp {...data} />
  )
}

and the recursive component:

const RecursiveComp = ({ obj, children }) => {
  const hasChildren = children && children.length

  return (
    <div className='class='App-box'>
      {obj}
      {hasChildren && children.map((item) => (
        <RecursiveComp key={children.obj} {...item} />
      ))}
    </div>
  )
}

CodePudding user response:

A non-recursive solution that returns an Array of React Elements, contained in a Fragment.

slice is used as reverse mutates the array.

['One','Two','Three'].slice().reverse().reduce((acc,str)=>
    React.createElement('div',{key:str }, [str].concat(acc))
, undefined)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

  • Related