Open In App

How do Styled Components work in terms of styling React components?

Styled Components is a library for React and React Native that allows you to write CSS in your JavaScript code in a more component-oriented way.

Working of Styled Components:

Example: We define a styled button component using the styled.button syntax. We interpolate JavaScript expressions to create dynamic styles based on the primary prop. Then, we use this styled button component in our MyComponent React component

import styled from 'styled-components';

// Create a styled component
const Button = styled.button`
background-color: ${props => props.primary ? 'blue' : 'white'};
color: ${props => props.primary ? 'white' : 'black'};
font-size: 16px;
padding: 10px 20px;
border-radius: 5px;
border: 2px solid ${props => props.primary ? 'blue' : 'black'};
`;

// Use the styled component in your React component
const MyComponent = () => {
return (
<div>
<Button>Normal Button</Button>
<Button primary>Primary Button</Button>
</div>
);
};
Article Tags :