Rashi Chouksey

Styled Components

An introduction to Styled Components

Styled-components is a library that allows you to use component-level styles in your React and React Native application that are written with the combination of JavaScript and CSS.

By the use of styled-components, React developers can write plain CSS inside your JavaScript code in React components.

Advantages of using Styled-components

  • There is no need of  class name,styled-components provide unique class names for your styles, thus eliminating the problems with class names duplications, misspellings, and overlaps..
  • We can customize components through props and there is no clashing with CSS selectors. styled-components make it easy to publish a React component to NPM.
  • Using React’s Context API, styled-components offers a ThemeContext that can you can pass a theme object directly to, making it very accessible in any of your components.
  • We can use SASS trademark syntax without having to install or set up SASS.

We can dynamically change the styles through props.

Installation & Setup the Local Environment

Check the following points to setup styled-components in your app 

  • First, we need to install styled-components library, for this we have to run command npm i styled-components –save
  • Then need to import the styled component library into our component by writing import styled from ‘styled-components’
  • We can create separate styled-component style file for each components for styling and can call inside the respected component file
  • Then we use the name of our variable we created as a wrapper around our JSX elements.
Example:- 

import React from 'react';
import styled from 'styled-components';

export const Wrapper = styled.div`
  margin: 20px;
  border: 5px  solid #ddd;
`;

export const Paragraph = styled.p`
  font-size: 14px;
  text-align: center;
`;


const Dashboard = () => {
return(
<Wrapper>
    <Paragraph> Styling React Components </Paragraph>
  </Wrapper>
)}
Share