React Code rendering as text and components are not being initiated

Viewed 61

I have created a component called "componentRepeater" who's job it is to render multiple instances of a child components. The props in that the "componentRepeater" contain includes the props for the child components and the number of repeats of the child component and the string (including props) for the child component.

The problem I am having is that once the string is completed it is rendering as text and therefore the component "componentRepeater" is not loading the required child components.

This is the code that initiates the component called "componentRepeater"

<ComponentRepeater 
  bookFormat={props.bookFormat} 
  data={timelineP2} 
  multiplayer='5' 
  childrenComponent='<PageTableTwoColumn bookFormat={props.bookFormat} data={timelineP2} />'
/> 

This is the code for component called "componentRepeater"

import React, { Fragment } from 'react';
import Timeline from '../layout/page-table-two-column'
import PageTableTwoColumn from '../layout/page-table-two-column'


export default function(props) {

  const multiplayer =  props.multipalyer
  const childrenComponent = props.childrenComponent

  const myRender = (props) => {
    var i;
    var myOutput = props
    for (i = 0; i < multiplayer-1; i++) {
      myOutput = myOutput + props
    }
    return (myOutput)
  }

  return (
    <Fragment>
      {myRender}
    </Fragment>
  );
}

3 Answers

It looks like you should call myRender() in the return:

  return (
    <Fragment>
      {myRender()}
    </Fragment>
  );

I think that approach is an overkill for that scenario dude :D take a look at this method for repeating a component a number of times first we create an array with the length of number of repeats, then we create a new array of jsx components by map() on that array and return the component we wan to replicate; ( its better to wrap the child component in parent and then access it via props.children instead of passing it as string. )

...
<ComponentRepeater 
  bookFormat={props.bookFormat} 
  data={timelineP2} 
  multiplayer='5' 
> 
  <PageTableTwoColumn bookFormat={props.bookFormat} data={timelineP2} />
</ComponentRepeater>
...

and then inside the repeater

//inside the jsx block
{[...new Array(repeats)].map( _ => props.children)}

and here is a example of how to use this approach:

function ChildComponent(){
  return (
    <span>hey I'm a component!</span>
  )
}

function App() {
  // 5 is an example you can use some props to initiate it;
  let repeats = 5;
  return (
    <div className="App">
      <header className="App-header">
        <p>A really nice header</p>
      </header>
      {[...new Array(repeats)].map( _ => <ChildComponent key={Math.random()}/>)}
    </div>
  );
}

take out the quotes in your childrenComponent, i think it suppose to be like this

childrenComponent={<PageTableTwoColumn bookFormat={props.bookFormat} data={timelineP2}/>}
Related