Typically, we usually include individual values in additional styling properties. However, it is still entirely feasible to provide a collection of CSS rules (a CSSObject).
To start, you must utilize an interpolation function to adjust the style according to runtime props:
const StyledButton = styled.div<{
hoverStyle?: CSSProperties
}>`
color: black;
background: blue;
// How can I incorporate the hoverStyle here?
${(props) => props.hoverStyle && inlineRules(props.hoverStyle)}
`
In this case, I employed an inlineRules
function to translate the CSSObject into a series of rules:
function inlineRules(rulesObj: CSSProperties) {
return Object.entries(rulesObj).map(([property, value]) => `${property}: ${value};`).join('');
}
Now, considering the "hoverStyle" designation of your styling property, it suggests that these rules should only apply on :hover
rather than directly merging with the primary styles of your <div>
. Consequently, they need to be placed within a nested block, wherein you can employ the &
symbol to reference the self style:
&
signifies all instances of the component and is utilized for implementing broad overrides
&:hover {
${(props) => props.hoverStyle && inlineRules(props.hoverStyle)}
}
Experience a live demonstration on CodeSandbox: https://codesandbox.io/s/sleepy-brook-h515v7?file=/src/App.tsx
Please note: In styled-components, CSS rules are formatted using standard "kebab-case," while CSSProperties
follow camelCase (e.g., "background-color" versus "backgroundColor" in your scenario). Within the aforementioned demo, I implemented a template literal conversion type to convert them to kebab-case, referencing TypeScript add kebab case types form actual camel case keys