Moving to Styled Components (from here on in known as SC as it's a pain to type) from SASS can be head work and can make you feel like you don't know CSS anymore. To aid in the conversion process this is a very high level overview of how to do the equivalents of SASS in SCs as the official documentation is often left wanting for this sort of thing.
Assume one of following imports is always called in the SC examples where appropriate but not both
import styled from "styled-components"
import styled,{css} from "styled-components"
With that out of the way...
This one is pretty simple:
const myVar = 'red';
const componentStyled = styled.div`
color: ${myvar};
`}
The constant/variable has to be defined outside of the SC
@mixin example($color){
color: $color;
}
.aClass {
@include example(red);
}
This can be accomplished in a number of ways through SC depending on your requirements.
The simplest way without any parameter requirements:
const exampleMixin =`
color: red;
`;
const componentStyled = styled.div`
${exampleMixin}
`;
This could also be thought of as the equivalent of a SASS placeholder.
With parameters:
function exampleMixin(color) {
return `
color: ${color};
`;
}
const componentStyled = styled.div`
${exampleMixin('red')}
`;
Sometimes your "mixin" will need access to the props passed to it:
const exampleMixin = css`
color: url(${props => props.error ? "red" : "black"});
`;
const componentStyled = styled.div`
${exampleMixin}
`;
The @content directive lets us pass additional properties into the mixin as so:
@mixin exampleMixin{
@supports(display: grid) {
@content;
}
}
.class {
width: 100px;
@include exampleMixin {
width: 200px;
}
}
As a SC this will take the form of:
const forModernBrowsers = (...args) => css`
@supports(display: grid) {
${css(...args)}
}
`;
const componentStyled = styled.div`
width: 100px;
${forModernBrowsers`
width: 200px;
`}
`;
We can take the previous example further and make it a little more useful:
const browser = {
ie: (...args) => css`
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
${ css(...args) }
}
`,
modern: (...args) => css`
@supports(display: grid) {
${ css(...args) }
}
`
}
const componentStyled = styled.div`
width: 100px;
browser.ie`
width: 200px;
`}
${browser.modern`
width: 400px;
`}
`;