I am migrating from css to styled-components
.
My react component looks like the following:
class Example extends React.Component {
........code here
render() {
return (
<div
className={ this.state.active ? "button active" : "button" }
onClick={ this.pressNumber }
>
<Number>{ this.props.number }</Number>
</div>
)
}
}
const Number = styled.div`
color: #fff;
font-size: 26px;
font-weight: 300;
`;
and my css looks like this:
.button {
height: 60px;
width: 60px;
}
.active {
animation-duration: 0.5s;
animation-name: highlightButton;
}
@keyframes highlightButton {
0% {
background-color: transparent;
}
50% {
background-color: #fff;
}
100% {
background-color: transparent;
}
}
Does anyone know how I can add the active class/add two classes to an element using styled-components
? Nothing is jumping out at me from the docs.
If anything is unclear or further information is required please let me know.
To add active class using React styled-components, we can add props to the component. We create the keyframes with the keyframes tag and a keyframe string. Then we add the Button component with the styled. button tag.
While Styled Components doesn't have anything out of the box for mixins, per se, we can use it to achieve exactly what we need.
styled-components has a code snippet for SSR: https://styled-components.com/docs/advanced#server-side-rendering. However, since we're using ReactDOMServer for rendering the page, there's no need to use Babel.
One way to dynamically change css properties with styled components is to insert a custom prop into your React component and access said property using the dollar sign and curly braces commonly used for template literals. Our current example is testing to see if our use pointer prop is true.
The template literals in styled components can access props:
const Button = styled.button`
height: 60px;
width: 60px;
animation: ${
props => props.active ?
`${activeAnim} 0.5s linear` :
"none"
};
`;
...
<Button active={this.state.active} />
...
Reference here
And to add the keyframes animation, you'll need to use the keyframes
import:
import { keyframes } from "styled-components";
const activeAnim = keyframes`
0% {
background-color: transparent;
}
50% {
background-color: #fff;
}
100% {
background-color: transparent;
}
`;
Reference here
You can extend the style to overwrite certain properties and keep the others untouched:
render() {
// The main Button styles
const Button = styled.button`
height: 60px;
width: 60px;
`;
// We're extending Button with some extra styles
const ActiveButton = styled(Button)`
animation-duration: 0.5s;
animation-name: highlightButton;
`;
const MyButton = this.state.active ? ActiveButton : Button;
return (
<MyButton onClick={this.pressNumber}>
<Number>{ this.props.number }</Number>
</MyButton>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With