styled-components css`` returns unexpected output when called inside a function - leading and trailing comma and interpolates code instead of values - styled-components

EDIT: Actually I was wrong, the first example also doesn't work! It also interpolates the code!!
I'm experimenting with styled-components css prop api and I ran into the following problem:
This code works well:
const myCss = css<PropsWithTheme>`
width: 100px;
height: 100px;
color: ${props => props.theme.color};
`
const MyComponent = () => <div css={myCss.toString()} />
But the following does not:
const getCss = (color: strinbg) => css<PropsWithTheme>`
width: 100px;
height: 100px;
color: ${color}; // I tried injecting the color directly
color: ${() => color}; // And also returning it from a callback inside the css``, just as I would access props/theme
`
const MyComponent = () => <div css={getCss('red').toString()} />
The output css here is width: 100px; height: 100px; color: ,red,; ,() => color,;, which is obviously not valid.
Using template string interpolation to stringify the output solves the problem, but results in very bad readability due to Prettier enforcing this format:
const MyComponent = () => (
<div
css={`
${getCss('red')}
`}
/>
)
Unfortunately moving the inerpolation anywhere outside the css prop definition ( in component body or creating a stringify function) breaks the functionality (either prop/theme access, all css doesn't get applied at all).
It seems to be related to this issue: https://github.com/styled-components/styled-components/issues/1641, but the suggested solution there is to use the css helper function, which I'm already doing :(
Is there an easy fix to my problem?

Related

Styled components and scoping

I'm starting to work with styled-components and had a question about scoping.
This is just a dummy example but one that shows the point.
So I have a component. I setup a styled div called Wrapper then instead of creating another styled component to handle group, I thought be easier to just add a class to the inner div called .group and using nesting like in SCSS to style the inner div. This works but the problem with using className for the inner div is there could be a collision with global styles called .group
So, is there a way to avoid this with scoping somehow, or would I have to create another styled component called Group to handle that inner CSS ? Seems like a lot of boilerplate to have to add another styled component just to style the inner components.
const Wrapper = styled.div`
color: blue;
.group {
padding: 10px;
color: green;
}
`
const MyComponent = () => {
return (
<Wrapper>
<div className='group'>
<h1>heading text</h1>
<h2>subheading text</h2>
</div>
<div>This is my blue text</div>
</Wrapper>
);
}
Here is my globalStylesheet with group. Obviously this only has one style but it could have way more to handle grouped elements globally.
export default createGlobalStyle`
h1, h2, h3, h4, h5, h6 {
font-family: '.....';
}
.group {
background-color: red;
}
`;
I know I could also do
> div {
border: 1px solid red;
}
but I want to be able to be more explicit with a className
I think it's better to create another styled-component for group like
const Group = styled.div`
padding: 10px;
color: green;
`
So you can be sure that overwriting styles properly. And if there will be more styles in Wrapper, it stays less readable. Also you can easily replace Group component into children or make as parent(in this case you should rewrite .group style from Wrapper to another one).
In future to prevent boilerplate code you can rewrite existed styled-components like
const Timer = styled.div`
background: #ff5f36;
border-radius: 50%;
width: 48px;
height: 48px;
display: flex;
justify-content: center;
align-items: center;
font-family: GTWalsheim;
font-size: 32px;
color: #ffffff;
`
const TimeIsUp = styled(Timer)`
width: 172px;
border-radius: 8px;
`
EDIT
Also you can easily replace Group component into children or make as parent
I'll try to explain in code below
const MyComponent = () => {
return (
<Wrapper>
<div className='someClass'>
<Group> // so you can replace only your component, without rewriting any style
<h1>heading text</h1>
<h2>subheading text</h2>
</Group>
</div>
<div>This is my blue text</div>
</Wrapper>
);
}
I mean you can easily replace Group component to any place of code. While when you write style from parent as it was in Wrapper, you should replace this .group style from Wrapper to another element which is parent for .group

Target another component on hover using emotion-js

I understand this is very similar to Target another styled component on hover
However I would like to achieve the same effect with emotion-js
More specifically I am trying to recreate this example using emotion styled components
Here is my code and what I have tried.
import React from 'react';
import styled from '#emotion/styled';
import { Link } from 'gatsby';
const Dropdown = styled.div`
postition: relative;
display: inline-block;
`;
const Button = styled.div`
background-color: green;
color: white;
&:hover {
${DropDownContent} {
display: block;
}
}
`;
const DropDownContent = styled.div`
display: none;
position: absolute;
`;
const DropDownMenu = () => {
return (
<Dropdown>
<Button>Dropdown</Button>
<DropDownContent>
<Link to="/">Link 1</Link>
</DropDownContent>
</Dropdown>
);
};
export default DropDownMenu;
I would like the link to show up when I hover the button, but that is not working and I cannot figure out why
There are three issues here.
You're referencing DropdownContent before you've defined it. Rearrange your code so that the DropdownContent declaration comes before the tagged template literals that use it and you should be good to go.
The resulting css selector (something like button:hover .DropDownContent) does not match your HTML document, where DropDownContent is a sibling of Button.
Your position property on Dropdown is misspelled.
With all three issues resolved, your code may look something like this:
import React from 'react';
import styled from '#emotion/styled';
import { Link } from 'gatsby';
const Dropdown = styled.div`
position: relative;
display: inline-block;
`;
const DropDownContent = styled.div`
display: none;
position: absolute;
`;
const Button = styled.div`
background-color: green;
color: white;
&:hover + ${DropDownContent} {
display: block;
}
`;
const DropDownMenu = () => {
return (
<Dropdown>
<Button>Dropdown</Button>
<DropDownContent>
<Link to="/">Link 1</Link>
</DropDownContent>
</Dropdown>
);
};
export default DropDownMenu;
as #coreyward mentioned, rearrange the code.... and the
import styled from "#emotion/styled/macro";
and this will do the trick
This solution was already posted at Component selectors can only be used in conjunction with babel-plugin-emotion error while using emotion by https://stackoverflow.com/users/165215/ijk

How to test style of nested component jest-styled-components

Im testing using react-testing-library and jest-styled-components.
I have a wrapper component that renders the styles of its child button dependant on a selected prop passed to it.
This is the code:
const selectedStyles = css`
background-image: url(../image);
background-position: center;
background-repeat: no-repeat;
border-color: ${color.grey6};
height: 38px;
width: 58px;
& span {
display: none;
}
`;
const ButtonWrapper = styled.div`
& button {
font-size: 15px;
line-height: 20px;
padding: 8px 12px;
${props =>
props.selected
? css`
${selectedStyles}
`
: ""}
&:hover,
:focus {
${props =>
props.selected
? css`
${selectedStyles}
`
: ""}
}
}
`;
and the test
test("it renders the correct styles when selected ", () => {
const { container } = render(<CheckButton selected>Add</CheckButton>);
const button = container.querySelector("button");
expect(button).toHaveStyleRule("background-position", "center");
});
but its failing with "Property 'background-position' not found in style rules" which is true for the original button, however when its parent is passed the selected prop this style applies.
I am also doing snapshot testing with the component however not testing the props getting passed brings the test coverage down.
Can anyone help?
In general as far as nested styles testing is concerned, I would recommend testing directly the nested element.
I personally haven't figured out a way to test nested styles using the .toHaveStyle(``); (not even a simple
a {
text-decoration: none;
}
)
so I ended up querying for the exact component I wanted to test, eg:
expect(screen.getByText(/text-within-the-child-component/i)).toHaveStyle(`
text-decoration: none;
`);
In your specific case I believe the way to go is to render your component in your test directly with the props that trigger the styles you want for each case (selected in your code example).
For those who are facing the same problem toHaveStyleRule accept a third "options" parameter after property and value where you can path a modifier:
test("it renders the correct styles when selected ", () => {
render(<CheckButton selected>Add</CheckButton>);
const button = container.querySelector("button");
expect(screen.getByText("Add").parentElement).toHaveStyleRule("background-position", "center", { modifier: 'button' });
});
Here I state on the fact that "Add" is the button text and its parent is the component ButtonWrapper.
By the way, you should avoid as much as possible using querySelector (here I'm using react testing library).
https://github.com/styled-components/jest-styled-components

Reuse a 'mixin' with Styled Components across different files?

How can I reuse a collection of styles with Styled Components across different files?
With SASS I can define and use a mixin like so:
#mixin section( $radius:4px ) {
border-radius: $radius;
background: white;
}
.box { #include section(); }
With Styled Components you can extend a style, but this means I would need to import that component into every page. This is pretty cumbersome compared to how variables are available everywhere with the ThemeProvider.
https://www.styled-components.com/docs/basics#extending-styles
Just adding on to the answer by #Evanss
You can make the mixin a function (as in OP) by doing:
const theme = {
sectionMixin: (radius) => `border-radius: ${radius};`
}
and then use it like:
const Button = styled.button`
${props => props.theme.sectionMixin('3px')}
`
or simply:
const Button = styled.button`
${({ theme }) => theme.sectionMixin('3px')}
`
You can create a string with multiple CSS rules and pass that to the ThemeProvider.
const theme = {
sectionMixin:
'background: white; border-radius: 5px; border: 1px solid blue;',
}
<ThemeProvider theme={theme}>

Using Material Icons with Styled Components

Just started playing around with Styled Components. Is there a way to style third party icons such as Material Design Icons? This is the code I have so far but obviously it isn't working. Relavant code is below Content component Thanks!
const MaterialIcon = (props) => <i className="material-icons">account_balance</i>;
const Icon = styled(MaterialIcon)`
background-color: green;
font-size: 50px;
`;
const CheckThisOut = props => (
<Wrapper>
<Header>
<h5>{props.title}</h5>
<Icon />
</Header>
<Divider />
<Content>
<p>5% of all participants in this campaign were first time users.</p>
</Content>
</Wrapper>
);
export default CheckThisOut;
For the styled(AnyComp) notation to work AnyComp needs to accept the incoming className prop and attach it to a DOM node.
For your example to work MaterialIcon has to use the passed in className, otherwise the styles are injected but no DOM node is targeted:
const MaterialIcon = (props) => (
<i className={`material-icons ${props.className}`}>account_balance</i>
);
// WORKS 🎉
const Icon = styled(MaterialIcon)`
background-color: green;
font-size: 50px;
`;
See our documentation page about styling any component for more information!
I know this is an old post, but here's another way to write it as a single expression. Using styled components' .attrs() (see docs) for the class name and the CSS ::after selector for the icon name.
const ThumbUp = styled.i.attrs(() => ({ className: "material-icons" }))`
background-color: green;
font-size: 50px;
&:after {
content: "thumb_up";
}
`;
Writing this in a more generic way will allow you to use it for any of the available icons. This makes use of styled component ability to adapt based on props (see styled components docs for more info).
const MaterialIcon = styled.i.attrs(() => ({ className: "material-icons" }))`
background-color: green;
font-size: 50px;
&:after {
content: ${props => props.iconName || "help"};
}
`;
Which you could then use like this:
<MaterialIcon iconName="check" />

Resources