joekevinrayan96
joekevinrayan96

Reputation: 634

Rendering a component within another component

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.

Upvotes: 0

Views: 2814

Answers (2)

Emin TATLI
Emin TATLI

Reputation: 82

You have to add {props.children} into the component if you want to render what's inside like this:

for Component1

const Test=(props)=>{
    return <>
    {props.children}
    </>
}

for Component2

const Test2=(props)=>{
    return <>
    {props.children}
    </>
}

for App.js

   <Test>
     <Test2>
       asd
     </Test2>
   </Test>

Upvotes: 1

Nicholas Tower
Nicholas Tower

Reputation: 84912

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>
  );
};

Upvotes: 1

Related Questions