4. React Composition - florypaul/ReactJS GitHub Wiki

Composition is:

  • Creating reusable code which can be used between components
  • Basically a wrapper/shell component which can be used between components example: A box having curved border and drop-shadow which is a common style in an overlay and alert box
  • Another example is toggle logic which is common in an accordion and in a Edit component
  • This technique prevents us from building too many similar components containing duplicate code and allows us to build fewer components that can be reused anywhere within our application, making them easier to understand and maintain for your team.
  • We build components from other components using explicit defined props or the implicit children prop, children is a reserved keyword (props.children) . https://codeburst.io/a-quick-intro-to-reacts-props-children-cb3d2fce4891

Card.js // note white space after 'card ' class is important

`import '.Card.css;

function Card(props){ constant classes = 'card ' + props.className;

return <div className={classes}>{props.children}</div> }`

Card.css

.card { border-radius: 12px; box-shadow: 0 1px 8px #cccccc; }

How to use Card.js wrapper in other components:

In ExpenseItem.js

<Card className='expense-item'> <ExpenseDate /> <h2> This Card still can have a different className </h2> </Card>

In ExpenseDate.js <Card className='expense-date'> <Date /> <h2> This Card still can have a different className </h2> </Card>

https://formidable.com/blog/2021/react-composition/#:~:text=What%20Is%20React%20Composition%3F,or%20the%20implicit%20children%20prop

⚠️ **GitHub.com Fallback** ⚠️