Let's say you need to create different elements that have similar style attributes but not the same. Traditional way to do this in CSS is to create a class and give that class to your elements. Then you create different classes, for the different attributes.
It will look like the example below;
styles.css
.box {
display: flex;
align-items: center;
justify-content: center;
width: 80px;
height: 80px;
border: 2px solid green;
border-radius: 6px;
}
.first-box {
color: red;
}
.second-box {
color: blue;
}
component.tsx
import React, { Component } from 'react';
import './styles.css';
class Component extends Component {
render() {
return (
<div>
<div className="box first-box">
<span>first box</span>
</div>
<div className="box second-box">
<span>second box</span>
</div>
</div>
);
}
}
And the output;
Now I will show you two different ways to achieve the same goal using styled-components.
- Using css`` markup
- Inheriting another styled component
1. Using css`` markup
In this example, we will save the shared piece of css values in a variable, and use that variable while we are creating the other components.
component.tsx
import React, { Component } from 'react';
import styled, { css } from 'styled-components';
const boxCss = css`
display: flex;
align-items: center;
justify-content: center;
width: 80px;
height: 80px;
border: 2px solid green;
border-radius: 6px;
`;
const FirstBox = styled.div`
${boxCss}
color: red;
`;
const SecondBox = styled.div`
${boxCss}
color: blue;
`;
class App extends Component {
render() {
return (
<div>
<FirstBox>
<span>first box</span>
</FirstBox>
<SecondBox>
<span>second box</span>
</SecondBox>
</div>
);
}
}
And we have the same visual result.
As you can see, we save the piece of css markup that we want to share in a variable, and use it as a text inside styled component definition.
2. Inheriting another styled component
In this example, we are going to create a component named that will have the shared attributes, and we will inherit this component while creating the other components.
component.tsx
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import styled, { css } from 'styled-components';
const Box = styled.div`
display: flex;
align-items: center;
justify-content: center;
width: 80px;
height: 80px;
border: 2px solid green;
border-radius: 6px;
`;
const FirstBox = styled(Box)`
color: red;
`;
const SecondBox = styled(Box)`
color: blue;
`;
class App extends Component {
render() {
return (
<div>
<FirstBox>
<span>first box</span>
</FirstBox>
<SecondBox>
<span>second box</span>
</SecondBox>
</div>
);
}
}
As you can see, we still have the same result.
I hope you liked it and it was useful for you. Thank you for reading.
You can follow me on LinkedIn for more content related to web development.
Top comments (1)
Another option would be to pass
color
into your component as an optional prop, with a default value if it’s not supplied.