Conditional CSS with styled tag
See original GitHub issueAsk your Question
Is it possible to do something like the following?
const TopLevelList = styled.ul<{ dark?: boolean }>`
border-top: 1px solid ${BrandColors.BORDER};
margin-top: 0;
${props => props.dark && ({
color: 'black',
})}
`;
Typescript is giving the following error:
Argument of type '(props: { dark?: boolean | undefined; }) => false | { color: string; } | undefined' is not assignable to parameter of type 'string | number | CSSProperties | ((props: { dark?: boolean | undefined; }) => TLength)'.
Type '(props: { dark?: boolean | undefined; }) => false | { color: string; } | undefined' is not assignable to type '(props: { dark?: boolean | undefined; }) => TLength'.
Type 'false | { color: string; } | undefined' is not assignable to type 'TLength'.
Type 'undefined' is not assignable to type 'TLength'.ts(2345)
Issue Analytics
- State:
- Created 4 years ago
- Reactions:15
- Comments:6
Top Results From Across the Web
conditional rendering in styled components - Stack Overflow
If you want to add multiple style properties you have to use css tag, which is imported from styled-components:.
Read more >Conditional Styling with Styled Components in React - Medium
Let's say, we want to conditionally change the color of a div. It will be displayed green, if a task is completed and...
Read more >Styled components - conditional styles with TypeScript
If you do not know how to start or would like to read more, here is the guide on how to write conditional...
Read more >Dark Mode: Conditional Styling using styled-components
Let's Code. We need to import styled from "styled-components", and we need to create a Container component that will render an div tag....
Read more >Advanced Usage - styled-components
Theming, refs, Security, Existing CSS, Tagged Template Literals, Server-Side Rendering and Style Objects.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
The readme has an example that shows you can do this:
No support for conditional CSS using the
styled
tag is the biggest hurdle for us moving to linaria from styled-components in a typescript project, however as suggested by @brandonkal I think something like this:which prevents “proper” React props unintentionally leaking to the DOM, something I’ve had issues with before, could be a nice solution (could even be the nicest solution!).
The tradeoff is losing type checking for the conditional styling, which may or may not be a big deal in your project.