I’m diving into React, and I’ve been experimenting with a Modal component using styled components. I’m trying to achieve a similar effect to Framer Motion’s motion.div
, but with styled components.
So far, I’ve got the basic structure working great:
"use client"
export default function Modal({ children }: { children?: ReactNode }) {
return <ModalStyled>{children}</ModalStyled>
}
Modal.Item = function ({ children }: { children?: ReactNode }) {
return (
<ModalItemStyled>
{children}
</ModalItemStyled>
)
}
It’s doing the job nicely! But, when I attempted to customize the styling using styled-components, like so:
export const CustomModalItem = styled(Modal.Item)`
background-color: red;
`
It seems like the styling isn’t being applied. 😕 I’m pretty sure I’ve missed something in the implementation. Any suggestions or guidance would be super appreciated! Also, I’m open to any tips for making the code even better. Thanks a bunch for your help! 🙌
"dependencies": {
"next": "latest",
"react": "^18",
"react-dom": "^18",
"styled-components": "^6.1.1"
}
2
Answers
Solved by adding className props :tada:
Styled-components doesn’t work with compound components by default. The styles you define in
CustomModalItem
won’t be applied directly to theModal.Item
component.To achieve the desired result, you can pass the styles as props to your
Modal.Item
component and apply them within its own styled component. Here’s an example:In the above example, the ModalItemStyled component accepts a prop called
customBackground
, and the background color is set based on the prop. This way, you can pass the customBackground prop when usingCustomModalItem
.You can use it this way: