React - dynamic child component

1

Very good to all and I hope you can help me, I have a component called Content which should be able to receive and then show according to the user's action one or another component, my question is, How I do to show a dynamic child component and what would be the best practice for it?

The content component is thus according to React in its part of Containment :

import React, { Component } from 'react';
class Contenido extends Component {
  constructor(props){
    super(props)
  }
  render() {
    return (
      <div className="container-fluid">
        {this.props.children}
      </div>
    )
  }
}
export default Contenido

and this is what I have so far in the component that matters to the Content component:

render () {
    return (
        < Contenido>
          < Publicaciones/>
        < /Contenido>
    )
  }

It is worth highlighting if you realize that within Content another component called Publications passes, the idea is to pass there dynamically, by default it would be Publications strong> but imagine that the user clicks on a menu and another component should be displayed there.

It would be something like this:

render () {
    return (
        < Contenido>
          < Publicaciones/> 
          ó
          < OtroComponente/>
          ó
          < OtroComponente/>
          ó
          ...
        < /Contenido>
    )
  }

I hope you can explain me.

    
asked by David Leonardo Molina Ruiz Dav 06.09.2018 в 13:09
source

1 answer

1

I found the solution, the idea is to make a function outside the main class of the component and invoke it by passing a props where then that function according to the value of the past props will evaluate which component it will show in the render, it would look something like this:

    import React, { Component } from 'react';
    import { componente1, componente2, componente3 } from '../src/components';
    class Contenido extends Component {
      constructor(props){
        super(props)

        this.state = {
          contenido: 1//Aqui es el valor que le pasare al props de la función
        };

      }

      render() {
        return (
          <div className="container-fluid">
            <LayoutContendio contenido={this.state.contenido} />
          </div>
        )
      }
    }

    function LayoutContendio(props) {

     switch(props.contenido) {

      case 1: return <componente1/>; break;
      case 2: return <componente2/>; break;
      case 3: return <componente3/>; break;
      default: return <componente1/>; break;

    } 

  }
  export default Contenido

If they are set, create a state that initially places a value of 1 to give it a default value and that value will show component1 but if the user clicks and changes the state to 2 would show the component2 and so on, I hope it serves them

    
answered by 08.09.2018 / 20:55
source