Enriching UI with Styled Components in React
CSS and styling
Imagine your website without CSS. Okay, let me simplify this for you. Imagine a skinless human body. Yeah, just the skeleton. Still not getting it? Okay, the image below will help you understand what I’m trying to say here-
As difficult it is for you to think of a skinless body, it is equally difficult for UI developers to think of a UI without CSS. CSS is a language that defines the way your web pages look. With CSS, web designers can add custom fonts, colors, layouts, and unique designs to web pages. Although the styling part is fairly simple, one needs to focus on all the aspects of CSS like the newly upgraded frameworks that are used for styling and managing web applications. Bootstrap, Semantic UI, and Material UI are some of the leading names. However, the real struggle starts when one has to apply conditional or generic CSS to many components. And thus the idea of variables and mixins came into existence. But as a React JS developer, I rely more on the styled-components that are used rarely due to the lack of awareness.
Styled Components — a brief
Styled Components were introduced by the React community and were meant to be successors to CSS Modules. Modules enable you to write CSS that’s scoped to a single component, and not leak to any other element on the page. Whereas, Styled Component is a kind of CSS in JS solution which means you don’t have external CSS files to fiddle with. Everything is in one place — logic, styling, and markup. Initially, this might feel a bit confusing but believe me it is very useful. Styled Components help in tracking the components that are rendered on a page and inject their styles, all this in a fully automated way. And you can combine Styled Components with code splitting to bring down load times for your users.
Installing Styled Components
npm install --save styled-components
Fire this command and your Styled Components are ready.
How to use Styled Components
import React from 'react';
import styled from 'styled-components';
const StyledButton = styled.button`
border-radius: 5px;
color: #fff;
padding: 10px 15px;
outline: none;
border: none;
cursor: pointer;
margin: 15px;`
const Application = () => {
return (
<div>
<StyledButton>Click me</StyledButton>
<StyledButton>Click for secondary Action</StyledButton>
</div>
)
}
At this point, a style button should be declared as …read more