How to pass components as parameters in react?

2

I need to pass a component as a parameter to be rendered from another component.

In the following example I want to render Title1 or Title2 within Profile

given the components:

export class Titulo1 extends React.Component {
  render () {
    return (<div><H2>this.props.nombre</H2><h3>this.props.apellido</H3></div>)
  }
}

export class Titulo2 extends React.Component {
  render () {
    return (<div><H1>this.props.nombre</H1><h2>this.props.apellido</H2></div>)
  }
}

and

export class Perfiles extends React.Component {
  render () {
   let perfiles= this.props.usuarios.map((usuario, index, coll) => {
        var props = {
          id: usuario.id,
          index: index,
          apellido: usuario.apellido,
          nombre: usuario.nombre
        }
         return (<Perfil {...props}>
            {React.createElement(this.props.extraComponent, props)}
          </Perfil>)
      }, this)
    }
    return ({perfiles})
  }
}

   export class Perfil extends React.Component {
      render () {
        return (<div><H2>this.props.id</H2>{this.props.children}</div>)
      }
    }

the goal is to call

<Perfiles extraComponent={Titulo1} usuarios={lista} />

or

<Perfiles extraComponent={Titulo2} usuarios={lista} />

as needed, but it does not let me give me an error in React.createElement (this.props.extraComponent, props) Any suggestions? thank you very much !!

    
asked by Jose Maria Toscano 07.03.2017 в 19:12
source

2 answers

3

You could try

<this.props.extraComponent {...props} />

The value you pass in the prop extraComponent is a Component as such, so you can use it with JSX syntax.

    
answered by 07.03.2017 / 22:46
source
1

There are two techniques for this: composition and inheritance, React uses composition, look at the documentation , an example where inheritance is used is Swing in Java or Android.

Focusing on React, the implementation is as follows

export class Perfiles extends React.Component {
    ...
    render () {
        return(
            <div>
                {this.props.children}
            </div>
        )
    }
}

later you use your component in the following way

<Perfiles usuarios={lista} />
    <Titulo nombre="Jose Maria" apellido="Toscano"/>
</Perfiles>
    
answered by 08.03.2017 в 15:33