SeekingTruth SeekingTruth - 12 days ago 5
Javascript Question

rendering multiple children of different types in react

In react you can do something like:

var Wrap = React.createClass({
render: function() {
return <div>{ this.props.children }</div>;
}
});

var App = React.createClass({
render: function() {
return <Wrap><h1>Hello word</h1></Wrap>;
}
});


This allows you to pass in a component to another. But what if Wrap had another div that you could put content into. So consider the following:

var Wrap = React.createClass({
render: function() {
return (
<div>
<ul className="icons">
// Another compoent should be passed here from App to render icons.
</ul>
{ this.props.children }
</div>
);
}
});

var App = React.createClass({
render: function() {
return <Wrap><h1>Hello word</h1></Wrap>;
}
});


In the above example you can see that not only do I want to pass in children of the
App
component but I also want to pass another component that is icons for the
ul
section. Is this possible?

If so, how?

Answer

I see two options:

  1. Pass the other component as prop, e.g.

    <Wrap icons={<Icons />}><h1>...</h1></Wrap>
    
  2. Pass two children two Wrap and render each of them in the appropriate places, e.g.

    <Wrap>
      <Icons />
      <h1>...</h1>
    </Wrap>
    
Comments