Styled Components is a popular library for styling React components using tagged template literals. It allows you to define component-level styles in JavaScript, keeping the styling scoped to the specific component. Here's a basic example of how to use Styled Components in React:
1. Install Styled Components:
First, install the library via npm or yarn:
npm install styled-components
2. Create Styled Components:
You can now create styled components directly in your React components.
import React from 'react';
import styled from 'styled-components';
// Define a styled component
const Button = styled.button`
background-color: #3498db;
color: white;
padding: 10px 20px;
font-size: 1rem;
border: none;
border-radius: 5px;
cursor: pointer;
&:hover {
background-color: #2980b9;
}
`;
const App = () => {
return (
<div>
<Button>Click Me</Button>
</div>
);
};
export default App;
3. Key Features:
- Scoped styling: The styles are scoped to the component, ensuring no clashes with global styles.
- Theming: Styled Components support themes, which allow you to easily switch between different visual styles.
- Props: You can dynamically change styles using props.
const Button = styled.button`
background-color: ${(props) => (props.primary ? "#3498db" : "#2ecc71")};
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
font-size: 1rem;
`;
const App = () => {
return (
<div>
<Button primary>Primary Button</Button>
<Button>Secondary Button</Button>
</div>
);
};
This gives you a flexible and dynamic way to style components in React. Would you like a more advanced example or more guidance on specific use cases?
Top comments (0)