dwjohnston
dwjohnston

Reputation: 11801

Is there any reason not to pass react components as properties?

Lets say we have a react component called ThreeModule which oh so cleverly displays three arbitary react components, (or even just arbitarily defined dom elements) in a row.

We can do this by setting react elements as state elements and passing them in as properties, as suggested in this answer:

class ModA extends React.Component{
  render () {
    return <div> this is ModA</div>
  }
}

class ModB extends React.Component{
  render () {
    return <div> this is ModB</div>
  }
}
class ModC extends React.Component{
  render () {
    return <div> this is ModC</div>
  }
}

class ThreeMod extends React.Component{

  render() {
  return (<div className = "ThreeMod"> 
    This is ThreeMod
    <div className ="left">   
      {this.props.moda}
    </div> 

    <div  className ="middle"> 
     {this.props.modb}
    </div> 

    <div  className ="right"> 
      {this.props.modc}
    </div> 

  </div> ); 

  }
}

class App extends React.Component {


  constructor() {

    super(); 
    this.state = {
      moda: <ModA/> ,
      modb: <ModB/> ,
      modc: <ModC/> 
    }
  }

  render() {
    function getRandomMod() {
      let rand =Math.floor(Math.random() * Math.floor(4));
      switch (rand) {
        case 0 : return <ModA/> 
        case 1: return <ModB/> 
        case 2: return <ModC/> 
        default: return "random text"; 
      }        
    }

    return (
      <div className="App">
        This is App

        <button onClick = {() => {
          this.setState({moda: getRandomMod() }
          )}}>randomise left </button> 

        <button onClick = {() => {
          this.setState({modb: getRandomMod() }
        )}}>randomise middle  </button> 

        <button onClick = {() => {
          this.setState({modc: getRandomMod() }
        )}}>randomise right</button> 

        <ThreeMod
          moda={this.state.moda}
          modb={this.state.modb}
          modc={this.state.modc}
          /> 
      </div>
    );
  }
}

ReactDOM.render(<App />,   document.body
);
div {
  border: solid 1px black; 
  padding: 0.2em;
}

.ThreeMod {
  display:flex; 
  flex-flow: row; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


<div id = "react"/> 

This works precisely for what I'm wanting to do - what I'm wondering is - is this the wrong way to do things? Is there a reason (eg. performance) not to do things this way?

Upvotes: 0

Views: 82

Answers (1)

felguerez
felguerez

Reputation: 920

I personally don't use this approach, but the presence of element ("a React element") and node ("anything that can be rendered") in the PropTypes documentation suggests that it's supported functionality.

Upvotes: 1

Related Questions