Search code examples
cssreactjssassstyled-components

Passing variables for media queries and rendering css in styled components?


im trying to write a more robust version of media queries in styled components.

I basically have a breakpoints file defined, i pass the respective breakpoint into another file which is rendered here:

const setMq = breakpoints => {
    return css` @media (min-width: ${breakpoints.from / 16}em) and (max-width: ${breakpoints.until / 16}em) {}`
};

Then in my actual styled component im trying to call it, but for whatever reason i cannot get the new colour of "blue" to render?

const ButtonStyled = styled.button`
    color: red;

    ${(setMq({
        from: breakpoints.xs,
        until: breakpoints.l,
     }),
     `
        color: blue;
    `)};
`;

Solution

  • I figured it out, anyone else needing the solution, i needed to change my main "function" to not output as an array but return as as string:

    const setMq = breakpoints => {
    return style => 
        `@media only screen and (min-width: ${breakpoints.from / 16}em) and (max-width: ${breakpoints.until / 16}em) { ${style} }`;
    };
    

    and then called with:

    const ButtonStyled = styled.button`
    color: red;
    
    ${setMq({
        from: breakpoints.xs,
        until: breakpoints.l,
        })`color: blue;`};
    `;
    
    export { ButtonStyled };