-
Notifications
You must be signed in to change notification settings - Fork 415
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conditional CSS with styled tag #409
Comments
Trying to compile and ignore the TS error has linaria throwing this:
|
Hi. I'm also wondering if there is a possibility to do this. With styled components we can have something like:
|
@neozgul This is currently not possible due to the way CSS is extracted at build time, the value of active is unknown at that time. You'd have to do this: <Tab className={cx(this.state.active && 'active')} onClick={this.handleButton}></Tab>
const Tab = styled.button`
width: 100%;
outline: 0;
border: 0;
height: 100%;
justify-content: center;
align-items: center;
line-height: 0.2;
&.active {
background: blue;
}
`; With my proposal, you could define props inside styled, specify if the prop should be forwarded, and thus keep all logic inside the CSS as you had before: <Tab active={this.state.active} onClick={this.handleButton}></Tab>
const Tab = styled.button`
width: 100%;
outline: 0;
border: 0;
height: 100%;
justify-content: center;
align-items: center;
line-height: 0.2;
&[props|active--] {
background: blue;
}
`; |
The readme has an example that shows you can do this:
|
Yes. That is the other approach. Be careful though @nhooyr. You'll notice color will leak into the DOM. The color attribute has special meaning in Safari. I've started just suffixing custom props that shouldn't make it to the DOM. So "color" would become "color$" |
No support for conditional CSS using the import React from "react";
import classnames from "classnames";
import { styled } from "linaria/react";
function Button() {
const [active, setActive] = React.useState(false);
return (
<StyledButton
className={classnames({ active })}
onClick={() => setActive(true)}
/>
);
}
const StyledButton = styled.button`
background: grey;
&.active {
background: blue;
}
`; 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. |
Ask your Question
Is it possible to do something like the following?
Typescript is giving the following error:
The text was updated successfully, but these errors were encountered: