9

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?

1
  • Aren't these two different components? <Icons />, which returns the <ul>, and whatever goes inside { this.props.children}. Then in App you can instantiate two different components rather than one. I think you'll continue to feel like you're fighting React if you pass components as props. Commented Oct 9, 2014 at 22:37

2 Answers 2

4

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> 
Sign up to request clarification or add additional context in comments.

2 Comments

how do you pass a component as a property? so if If I did var Icons = React.createClass({}); would it be as you did <Wrap icons={Icons} /> Also if I do the two children, how do I get the second children set? the first is this.props.children for the <h1></h1> but the second is?
You'd create the component like any other, e.g. <Wrap icons={<Icons />} />. this.props.children is actually either a single component or an array of components. There is a helper function available that will always return an array, but I can't remember it right now. If you pass two children, you can access the first one with this.props.children[0] and the second one with this.props.children[1].
1

Using Higher order components to do this is cleaner than accessing children by index or looping imo.

const wrap = (Icons) => class extends React.Component { render() { return ( <div> <ul className="icons"> <Icons {...this.props.iconProps} /> </ul> { this.props.children } </div> ); } }); class AppIcons extends React.Component { render: function() { return <div /> } }); class App extends React.Component { render: function() { return <Wrap iconProps={this.props}><h1>Hello word</h1></Wrap>; } }); const Wrap = wrap(AppIcons); ReactDOM.render(App, domContainerNode) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.