In my application I have a component that I want to style with the css prop from outside.
function Component({css}:{css?: React.CSSProperties}) {
// some stuff going on here
return (
<div
css={{
color: blue,
...css
}}
>
// some stuff going on here
</div>
)
}
The background is as follows:
I want to use Component
in different scenarios where I have to style the container based on the surrounding layout. E.g. flex, grid or in combination with some components I have to add different margins.
Now instead of introducing many props for all possible scenarios, I want to be able to style the container from outside the component.
E.g. usages of the component could be:
function Layout() {
return (
// some other components
<Component css={{margin: 12}}/>
// some other components
)
}
or
import {css} from "@emotion/react"
const style = css({margin: 12})
function Layout() {
return (
// some other components
<Component css={style}/>
// some other components
)
}
or
import {css} from "@emotion/react"
const style1 = css({margin: 12})
const style2 = css({color: 'red'})
function Layout() {
return (
// some other components
<Component css={[style1, style2]}/>
// some other components
)
}
I have the following problems:
newCss
it works as expectedReact.CSSProperties
is not the right prop type to handle all the possibilities of emotions css prop.Component
?The right way of achieving this functionality is modifying the component to accept extra props. This way the css prop passed into the component would be merged with the one within the component.
function Component({prop1, prop2, propN, ...props}) {
// some stuff going on here
return (
<div
css={{
color: blue,
}}
{...props}
>
// some stuff going on here
</div>
)
}
Now you can use additional styles on your component and it will be rendered properly.
function Layout() {
return (
// some other components
<Component css={{marginTop: "1em"}}/>
// some other components
)
}
The side effect of this solution that any additional prop would be passed directly to the HTML element inside the component that takes {...props}
.