And your Header/Body can access Card value using either useContext hook or as a render prop.
// Using React Hooks (available from v16.8.0 and on)Card.Header=({children})=>{constctx=useContext(CardContext);return<h1>{children||ctx.name}</h1>;};Card.Body=({children})=>{constctx=useContext(CardContext);return(<section><h2>Card Name: {ctx.name}</h2>{children}</section>);};// Using Render Props (before & excluding v16.8.0)Card.Header=({children})=>{return(<CardContext.Consumer>{ctx=><h1>{children||ctx.name}</h1>}</CardContext.Consumer>);};Card.Body=({children})=>{return(<CardContext.Consumer>{ctx=>(<section><h2>Card Name: {ctx.name}</h2>{children}</section>)}</CardContext.Consumer>);};
Now you can use Card/Header/Body like following and can also nest inside other elements.
functionApp(){return(<divclassName="App"><Card><Card.Header/><br/><Card.Header>Custom Header</Card.Header><articlestyle={{margin:"5rem"}}><Card.Body><h3>This is card body</h3></Card.Body></article></Card></div>);}
If you have an Egghead.io account, Kent C. Dodds has an Advaned React Component Patterns course, which discusses this technique in detail.
You first need a top-level
Cardcomponent.You can declare a static properties named
HeaderandBody(Capitalize them to adhere to React guideline)You can follow along here.
Then you need to implement those two static properties.
If you need to nest those
Card.Header/Bodycomponents, you need to use a context to pass top-level values available.So
Cardwould look like this,And your
Header/Bodycan accessCardvalue using eitheruseContexthook or as a render prop.Now you can use
Card/Header/Bodylike following and can also nest inside other elements.If you have an Egghead.io account, Kent C. Dodds has an Advaned React Component Patterns course, which discusses this technique in detail.
Thanks, Looks good