Welcome to our deep dive into the world of Styled Components in React JS! Today, we'll learn how to style your React components in a clean, maintainable, and reusable way.
Styled Components is a popular CSS-in-JS library for React. It lets you write CSS directly inside your components, making your styles easier to manage and reuse.
Scoped Styles: Styled Components automatically scopes your styles to the specific component they are applied to, preventing unwanted cascading and specificity issues.
Reusable Styles: You can easily create and reuse styles across multiple components.
Component-centric development: By integrating styles with components, you can better understand the visual representation of your components.
To use Styled Components, first, make sure you have React and Node.js installed. You can then install Styled Components using npm or yarn:
npm install styled-componentsor
yarn add styled-componentsLet's create a simple Button component with a styled div.
import React from 'react';
import styled from 'styled-components';
const Button = styled.div`
padding: 10px 20px;
font-size: 20px;
border-radius: 5px;
background-color: palevioletred;
color: white;
cursor: pointer;
`;
const App = () => {
return (
<div>
<Button>Click me!</Button>
</div>
);
};
export default App;In this example, we've created a Button component using styled.div, and we've styled it using CSS-like syntax. The styles will only apply to this specific Button component.
You can pass props to your styled components and change styles based on those props.
const Button = styled.div`
${props => props.primary && `
background-color: palevioletred;
color: white;
`}
${props => props.secondary && `
background-color: white;
color: palevioletred;
`}
`;
const App = () => {
return (
<div>
<Button primary>Click me!</Button>
<Button secondary>Hover me!</Button>
</div>
);
};In this example, we've created a Button component that can have either the primary or secondary prop. Depending on the prop, the background color and text color will change.
You can also style the children of your styled components.
const Heading = styled.h1`
color: palevioletred;
font-size: 2em;
& > span {
color: white;
}
`;
const App = () => {
return (
<div>
<Heading>
Welcome to CodeYourCraft <span>💫</span>
</Heading>
</div>
);
};In this example, we've styled the children of our Heading component by using the & selector followed by the tag name and space.
Component Naming: Name your components following React conventions.
Use CSS Media Queries: You can use CSS Media Queries to create responsive styles.
Use CSS Modules: If you're working in a larger project, consider using CSS Modules alongside Styled Components for better organization.
What does Styled Components do?
That's it for today! I hope you enjoyed learning about Styled Components. In the next lesson, we'll dive deeper into more advanced features and best practices. Stay tuned! 🚀