Reading some documentation of React-Bootstrap I found this example of how to use their Card component.
<Card style={{ width: '18rem' }}>
<Card.Body>
<Card.Title>Card Title</Card.Title>
<Card.Subtitle className="mb-2 text-muted">Card Subtitle</Card.Subtitle>
<Card.Text>
Some quick example text to build on the card title and make up the bulk of
the card's content.
</Card.Text>
<Card.Link href="#">Card Link</Card.Link>
<Card.Link href="#">Another Link</Card.Link>
</Card.Body>
</Card>
I am currently trying to create my own card and I would love to use that syntax. Instead of passing the entirety of my content by props, I would love to pass other components that would be kinda like dependencies of the first one.
I would gladly appreciate some help on this.
CodePudding user response:
What you are looking for is referred to as a "compound" component. Don't take what I did here line for line, but this is generally how they work. You can add as much code as you want to each one and give them state, props etc. Pretty easy.
const Title = ({ children }) => {
return (
<div>
<h2>{children}</h2>
</div>
)
}
const SubTitle = ({ children }) => {
return (
<div>
<h3>{children}</h3>
</div>
)
}
const Text = ({ children }) => {
return (
<div>
{children}
</div>
)
}
const Link = ({ href, children }) => {
return (
<a href={href}>
{children}
</a>
)
}
const Body = ({ children }) => {
return (
<div>
{children}
</div>
)
}
const Card = ({ children, style }) => {
return (
<div style={style}>
{ children }
</div>
)
}
Card.Title = Title
Card.SubTitle = SubTitle
Card.Text = Text
Card.Link = Link
Card.Body = Body
export default Card