Skip to content

Instantly share code, notes, and snippets.

@Hiweus
Last active May 22, 2024 16:57
Show Gist options
  • Save Hiweus/60546099ea716ac7d3955050a39a739e to your computer and use it in GitHub Desktop.
Save Hiweus/60546099ea716ac7d3955050a39a739e to your computer and use it in GitHub Desktop.
Example of composite component in react
.card {
background: red;
color: white;
font-weight: 500;
display: flex;
justify-content: space-between;
align-items: center;
width: 900px;
}
.container-buttons {
background: blue;
padding: 5px;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: normal;
}
import { ReactNode } from 'react'
import reactLogo from './assets/react.svg'
import './App.css'
function ContainerRoot({ children }: { children: ReactNode }) {
return (
<div className="card">
{children}
</div>
)
}
function TextContainer({text}: {text: string}) {
return (
<p>
{text}
</p>
)
}
function ImageContainer({link, image}: {link?: string, image: string}) {
return (
<a href={link} target="_blank">
<img src={image} className="logo react" alt="React logo" />
</a>
)
}
function ActionsContainer({ children }: { children: ReactNode }) {
return <div className='container-buttons'>
{children}
</div>
}
function ActionItem({ onClick, children }: { children: ReactNode, onClick?: () => Promise<void> }) {
return <button onClick={onClick}>
{children}
</button>
}
const Container = {
Root: ContainerRoot,
Text: TextContainer,
Image: ImageContainer,
Actions: ActionsContainer,
Action: ActionItem,
}
function App() {
return (
<Container.Root>
<Container.Image image={reactLogo} link='https://google.com'/>
<Container.Text text="Friend i'm here" />
<Container.Actions>
<Container.Action onClick={async () => console.log('oi')}>
1
</Container.Action>
<Container.Action onClick={async () => console.log('oi')}>
2
</Container.Action>
<Container.Action onClick={async () => console.log('oi')}>
3
</Container.Action>
<Container.Action onClick={async () => console.log('oi')}>
4
</Container.Action>
</Container.Actions>
</Container.Root>
)
}
export default App
@Hiweus
Copy link
Author

Hiweus commented May 22, 2024

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment