Jobs
Blogs
Courses
Mentorship
Partners
For Employers
e2e logo

Styled Component in React

mac

Styled Component in React


                     There are many options you can take when it comes to styling a React application. The traditional way would be to create an external CSS file. Styled-components is a popular library that is used to style React applications. It allows you to build custom components by writing actual CSS in your JavaScript.


Benefits of using styled-components:

 Automatic critical CSS :

       Styled-components keeps track of which components are rendered on a page and only adds their styles

 No class name bugs :

       Styled-components generates a unique class name for the styles

 Easier deletion of CSS:

       Styles are tied to a specific component rather than being added as a class name

 Simple dynamic styling :

       Styles can be added to a component based on props or a theme

 Painless maintenance: 

      Styles added to a component is done all in one place, rather than across multiple files

 Automatic vendor prefixing :

       Styled-components handles all of this.


Installation:

       The styled-components framework can be installed using either NPM or Yarn:

 Then imported into React as follows:


Create  Styling components:

               Styled-components utilises tagged template literals to style components. So in order to style our components we need to declare a variable that matches the component name.You can  define what type of HTML element to render (div, h1, p, or button…):

Let's see in example:

Create a Styled-Component.

Styled-Component.js

 Import the Styled-Component in App.js


App.js

I hope this article was helpful for you to get started using styled-components with React.

Thanks for reading!