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?
React allows us to render one component inside another component. It means, we can create the parent-child relationship between the 2 or more components.
Fragments in React Now you can render multiple DOM nodes. In order to do this, wrap it inside a parent div which essentially makes it a single DOM node with multiple elements inside it. Fragments in React do not deviate much from their literal meaning.
Now, we know that React components re-render themselves and all their children when the state is updated.
I see two options:
Pass the other component as prop, e.g.
<Wrap icons={<Icons />}><h1>...</h1></Wrap>
Pass two children two Wrap
and render each of them in the appropriate places, e.g.
<Wrap>
<Icons />
<h1>...</h1>
</Wrap>
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With