How to pass in a react component into another react component to transclude the first component's content?
You can use this.props.children
to render whatever children the component contains:
const Wrap = ({ children }) => <div>{children}</div>
export default () => <Wrap><h1>Hello word</h1></Wrap>
Pass react component as props
Using this.props.children
is the idiomatic way to pass instantiated components to a react component
const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>
When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div
or span
):
const Label = props => <span>{props.children}</span>
const Button = props => {
const Inner = props.inner; // Note: variable name _must_ start with a capital letter
return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>
If what you want to do is to pass a children-like parameter as a prop, you can do that:
const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />
After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.
React.js: Wrapping one component into another
Try:
var Wrapper = React.createClass({
render: function() {
return (
<div className="wrapper">
before
{this.props.children}
after
</div>
);
}
});
See Multiple Components: Children and Type of the Children props in the docs for more info.
Related Topics
Socket.Io 1.X: Use Websockets Only
How to Update States 'Onchange' in an Array of Object in React Hooks
CSS Media Queries and Jquery Window .Width() Do Not Match
Aggregation Filter After $Lookup
Convert JavaScript Array of 2 Element Arrays into Object Key Value Pairs
How to Resolve Typeerror: Cannot Convert Undefined or Null to Object
No Ways to Have Class-Based Objects in JavaScript
React Input Defaultvalue Doesn't Update with State
Sort Object Properties and JSON.Stringify
Es6 Modules Implementation, How to Load a JSON File
Adding Prototype to JavaScript Object Literal
How to Handle Circular Dependencies with Requirejs/Amd
Find Day Difference Between Two Dates (Excluding Weekend Days)
How to Block Users from Closing a Window in JavaScript
Regex for Number with Decimals and Thousand Separator