Creating a user interface with React is a pleasure for many developers, but ensuring those interfaces are both visually appealing and easy to maintain can be a bit tricky. That's where Styled-Components comes into play.
In the previous blog you see how to use tailwindcss in react app for faster designing your apps with static classes. Styled-Components is a fantastic library that simplifies the process of styling your React components. In this blog, we’ll see what React Styled Components are, how to use them, and how they can enhance your UI design skills.
What are Styled-Components?
Styled-Components is a library that allows you to write CSS directly within your JavaScript files (CSS-in-JS), ensuring that your styles are scoped to individual components. Rather than managing separate CSS files, you define your styles alongside your component logic.
Styled-Components utilizes tagged template literals in JavaScript to generate unique class names, preventing style collisions. At its essence, it focuses on encapsulation and simplicity.
Styled-Components simplifies the process of maintaining, reusing, and modifying your styles over time. Additionally, it integrates seamlessly with React’s component-based architecture.
Getting Started with Styled-Components
In order to start using React Styled Components, you first need to install the library. Open your terminal in the React project folder and run:
npm install styled-components
# Install this Additional Types, if you're using typescript
npm install @types/styled-components
Once installed, you can immediately start using Styled Components in your React app. Look how simple it is to install and use the styled-components library in React.
How to create a React Styled Component?
Creating a styled component is super simple. Let’s say we want to create a button with custom styles. Instead of writing CSS in a separate file, you can do this:
import styled from 'styled-components';
const StyledButton = styled.button`
background-color: #4caf50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
&:hover {
background-color: #45a049;
}
`;
const App = () => (
<StyledButton>Click Me</StyledButton>
);
export default App;
Here, we’ve created a StyledButton
component that can be reused anywhere in your app. Notice how you can also use pseudo-classes like :hover
. This is all standard CSS but with the added benefit of React-style encapsulation.
Dynamic Styling with Props
One of the coolest features of Styled Components is the ability to dynamically style components based on props. Let’s modify our button to accept a primary
prop:
const StyledButton = styled.button`
background-color: ${(props) => (props.primary ? '#007BFF' : '#4caf50')};
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
&:hover {
background-color: ${(props) => (props.primary ? '#0056b3' : '#45a049')};
}
`;
const App = () => (
<div>
<StyledButton primary>Primary Button</StyledButton>
<StyledButton>Secondary Button</StyledButton>
</div>
);
We’ve made our component more versatile and reusable with just a few lines of code. You can pass any prop you like and use it to style your components dynamically.
Using Styled-Components for Layouts
In React Styled Components aren’t just for small elements like buttons; they’re fantastic for creating layouts too. Let’s say we want a flexbox container and some grid elements:
const FlexContainer = styled.div`
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f4f4f4;
`;
const GridItem = styled.div`
width: 100px;
height: 100px;
background-color: #007BFF;
margin: 10px;
`;
const App = () => (
<FlexContainer>
<GridItem />
<GridItem />
<GridItem />
</FlexContainer>
);
With these simple components, you can structure complex layouts while keeping your code clean and manageable.
Media Queries with Styled-Components
Responsive design is essential, and Styled-Components makes adding media queries straightforward. Here’s how you can include them:
const ResponsiveBox = styled.div`
width: 50%;
height: 100px;
background-color: #ff5722;
@media (max-width: 768px) {
width: 100%;
}
`;
const App = () => <ResponsiveBox />;
The box will take up 50%
of the width on larger screens but will become 100%
wide on screens smaller than 768px
. No external CSS files are required!
Theming with Styled-Components
Theming is where Styled-Components really shines. You can create a central theme and apply it across your app using the ThemeProvider
:
import { ThemeProvider } from 'styled-components';
const theme = {
primary: '#007BFF',
secondary: '#4caf50',
};
const StyledButton = styled.button`
background-color: ${(props) => props.theme.primary};
color: white;
padding: 10px 20px;
`;
const App = () => (
<ThemeProvider theme={theme}>
<StyledButton>Click Me</StyledButton>
</ThemeProvider>
);
With theming, you can maintain consistency across your application while making it easier to adapt to different designs in the future.
Using Styled-Components with Custom CSS
If you already have CSS files or stylesheets, you can use Styled-Components to integrate those styles. For instance, you can extend existing styles:
const BaseButton = styled.button`
padding: 10px 20px;
border-radius: 5px;
`;
const CustomButton = styled(BaseButton)`
background-color: #4caf50;
color: white;
`;
const App = () => <CustomButton>Click Me</CustomButton>;
This approach allows you to leverage existing styles while keeping the flexibility of Styled-Components.
Using Styled-Components with TailwindCSS
If you love TailwindCSS but also want the benefits of Styled-Components, you can combine the two. Styled-Components can wrap Tailwind classes for a hybrid approach:
const TailwindButton = styled.button.attrs({
className: 'bg-blue-500 text-white py-2 px-4 rounded',
})``;
const App = () => <TailwindButton>Click Me</TailwindButton>;
This method lets you enjoy the utility-first nature of Tailwind alongside the component-based encapsulation of Styled-Components.
Using Styled-Components with design libraries
Design libraries like Material-UI or Ant Design are popular in React development. Styled-Components can be used to customize their components. Here’s an example with Material-UI:
import styled from 'styled-components';
import Button from '@mui/material/Button';
const StyledMuiButton = styled(Button)`
background-color: #4caf50 !important;
color: white !important;
&:hover {
background-color: #45a049 !important;
}
`;
const App = () => <StyledMuiButton>Click Me</StyledMuiButton>;
This approach gives you the best of both worlds—design consistency and the ability to fine-tune your styles.
Final Thoughts
Styled-Components is a revolutionary tool for modern UI development with React. It provides a clean, reusable, and dynamic approach to styling components, which helps keep your codebase organized and easy to maintain.
Whether you're working on small components, creating layouts, or setting up themes, Styled-Components has everything you need.
Its compatibility with design libraries, custom CSS, and even utility-first frameworks like TailwindCSS makes it an exceptionally flexible option.
If you haven't explored Styled-Components yet, consider using it in your next project, it could become your go-to styling solution.
This Blog Originally Posted at Programmingly.dev. Understand & Learn Web by Joining our Newsletter for Web development & Design Articles
Top comments (0)