I am trying to render components inside another component in the following way. Even when I try to render div elements within the component it's not being displayed.
const Sandbox = () => {
return (
<div>
<RenderHtml
Title="This is the title"
Description="This is the description">
<Example message="Hello World" />
<h1>Render somthing here</h1>
</RenderHtml>
</div>
);
};
export default Sandbox;
Below is the code for RenderHtml component
const MyCard = styled(Card)();
const RenderHtml = (props: any) => {
return (
<MyCard>
<div
style={{
display: "flex",
justifyContent: "space-between",
flexDirection: "column",
}}
>
<Typography variant="h1" sx={{ textAlign: "center" }}>
{props.Title}
</Typography>
<Typography variant="subtitle1" sx={{ textAlign: "center" }}>
{props.Description}
</Typography>
</div>
</MyCard>
);
};
export default RenderHtml;
I went through different examples and tutorials couldn't understand how I can render. If someone could help me out with this please.
CodePudding user response:
You have to add {props.children} into the component if you want to render what's inside
Component1
const Test=(props)=>{
return <>
{props.children}
</>
}
Component2
const Test2=(props)=>{
return <>
{props.children}
</>
}
App.js
<Test>
<Test2>
asd
</Test2>
</Test>
CodePudding user response:
When you render components inside another component, these get passed to the outer component as the prop children
. For the inner components to have any effect, the outer component needs to do something with the children
prop, which your RenderHtml
component currently doesn't do.
For example, if you want the children to be rendered after the title but inside the div you can do this:
const RenderHtml = (props: any) => {
return (
<MyCard>
<div
style={{
display: "flex",
justifyContent: "space-between",
flexDirection: "column",
}}
>
<Typography variant="h1" sx={{ textAlign: "center" }}>
{props.Title}
</Typography>
<Typography variant="subtitle1" sx={{ textAlign: "center" }}>
{props.Description}
</Typography>
{props.children}
</div>
</MyCard>
);
};