React compound components
22 Apr, 2021
👋 FYI, this note is over 6 months old. Some of the content may be out of date.
import React, { useContext } from 'react'
const Context = React.createContext()
const List = ({ isSmall = false, children, ...props }) => (
<ul {...props} style={{ padding: isSmall ? '5px' : '10px' }}>
<Context.Provider value={isSmall}>{children}</Context.Provider>
</ul>
)
const ListItem = ({ children, ...props }) => {
const isSmall = useContext(Context)
return (
<li {...props} style={{ padding: isSmall ? '5px' : '10px' }}>
{children}
</li>
)
}
export { List, ListItem }
<List isSmall>
<ListItem>Cat</ListItem>
<ListItem>Dog</ListItem>
</List>
Another example: https://egghead.io/lessons/react-write-compound-components
← Back home