React Styled-Components Library

Useful : 1] Click 2] Click 


There are many ways to style a React component. There’s the traditional way of using CSS in external CSS files, which then passes a string as the className prop to reference them. But as the project grows CSS files begin to get bulky, clumsy, and complex. One great solution to this is the introduction of SASS. Although SASS helps, you’ll eventually deal with the same issue due to the sheer number of SCSS files a project can have.

Finally, CSS-in-JS is a technique where JavaScript is used to style components. When this JavaScript is parsed, CSS is generated as a style element and attached directly on top of the DOM. There are a host of CSS-in-JS frameworks out there,Styled-components is, however, arguably the most popular. 

Styled-Components is a CSS-in-JS styling solution for React. It allows you to build custom components by writing actual CSS in your JavaScript. Styled components are React components that you write with the styled-components library, where you can style your components with plain CSS inside your JavaScript code.

In the below example you can see how we use styled-components. We basically use the styled() function to create a styled component. The styled() takes a wrapper element which is used as the base element for styling. The base element can be anything (div,button,h1 etc),we pass it by following this syntax : "styled.<AnyElement>", then we pass the CSS to style the passed base element.




import "./App.css";
import * as React from "react";
import styled from "styled-components";

// NOTE : It is better practice to store it
// externally and then import it
const StyledButton = styled.button`
  margin:10px;
  background-color: aqua;
  font-weight: bold;
  font-size: 40px;
  padding: 25px;
  border-radius: 10px;
`;

export default function SimpleContainer() {
  return(
      <div>
          <StyledButton> Button 1 </StyledButton>
          <StyledButton> Button 2 </StyledButton>
          <StyledButton> Button 3 </StyledButton>
      </div>
  )
}

NOTE : By exporting these styled components externally and then importing whenever required,we can create custom components which are self contained with all the css scoped to themselves only.

---------------------------------------------------------------------------------------------------------------


Adapting based on Props

When using styled components,we also have the ability to pass CSS values as props. All we have to do is define a function as value for the CSS property,the styled-components library will automatically inject the component's props as function argument,from there we can then manage the prop values as per our need.




import "./App.css";
import * as React from "react";
import styled from "styled-components";

// NOTE : It is better practice to store it
// externally and then import it
const StyledButton = styled.button`
  margin:10px;
  // If buttonColor prop value is empty,set it as 'yellow'
  background-color:
       ${(props)=> props.buttonColor!= null ? props.buttonColor : "yellow"};
  font-weight: bold;
  font-size: 40px;
  padding: 25px;
  border-radius: 10px;
`;

export default function SimpleContainer() {
  return(
      <div>
          <StyledButton buttonColor="#ff0000"> Button 1 </StyledButton>
          <StyledButton buttonColor="#00ff00"> Button 2 </StyledButton>
          <StyledButton > Button 3 </StyledButton>
          <StyledButton > Button 4 </StyledButton>
      </div>
  )
}


---------------------------------------------------------------------------------------------------------------


Extending Styles

When creating components we often com across a scenerio where we might want to reuse the styles from another styled component and change just one or two CSS properties, we can do this by extending an existing styled component. To easily make a new component that inherits the styling of another, just wrap it in the styled() constructor.



import "./App.css";
import * as React from "react";
import styled from "styled-components";


const StyledButton = styled.button`
  margin:10px;
  // If buttonColor prop value is empty,set it as 'yellow'
  background-color:
       ${(props)=> props.buttonColor!= null ? props.buttonColor : "yellow"};
  font-weight: bold;
  font-size: 40px;
  padding: 25px;
  border-radius: 10px;
`;

const FancyButton = styled(StyledButton)`
// If buttonColor prop value is empty,set it as 'green'
background-color:
       ${(props)=> props.buttonColor!= null ? props.buttonColor : "green"};
font-weight: 400;
border: 5px solid red;
`

export default function SimpleContainer() {
  return(
      <div>
          <StyledButton buttonColor="#ff0000"> Simple </StyledButton>
          <FancyButton> Fancy </FancyButton>
      </div>
  )
}


Polymorphic prop

Sometimes we might want the CSS styles of an existing component but may want a different wrapper element, for this we can use styled-component's "aspolymorphic prop. So If you want to keep all the styling you've applied to a component but just switch out what's being ultimately rendered (be it a different HTML tag or a different custom component), you can use the "as" prop to do this at runtime.



import "./App.css";
import * as React from "react";
import styled from "styled-components";


const StyledButton = styled.button`
  margin:10px;
  // If buttonColor prop value is empty,set it as 'yellow'
  background-color:
       ${(props)=> props.buttonColor!= null ? props.buttonColor : "yellow"};
  font-weight: bold;
  font-size: 40px;
  padding: 25px;
  border-radius: 10px;
`;


export default function SimpleContainer() {
  return(
      <div>
    <StyledButton buttonColor="#ff0000"> This is a Button </StyledButton>
          {/* Replace button with div tag */}
    <StyledButton buttonColor="#ff0000" as="div"> This is a Div </StyledButton>
      </div>
  )
}


---------------------------------------------------------------------------------------------------------------


Pseudoclasses

A pseudo-class is used to define a special state of an element. We use them as selectors to apply different CSS to elements as their state changes,one most used pseudoclass is 'hover'. The '& ' a single ampersand refers to all instances of the component; it is used for applying broad overrides.

Example] The background of button changes when we hover over it.


import "./App.css";
import * as React from "react";
import styled from "styled-components";


const StyledButton = styled.button`
  margin:10px;
  // If buttonColor prop value is empty,set it as 'yellow'
  background-color:
       ${(props)=> props.buttonColor!= null ? props.buttonColor : "yellow"};
  font-weight: bold;
  font-size: 40px;
  padding: 20px;
  border-radius: 10px;
  &:hover {
    background-color: white;
  }
`;


export default function SimpleContainer() {
  return(
      <div>
          <StyledButton buttonColor="#ff0000"> This is a Button </StyledButton>
      </div>
  )
}


---------------------------------------------------------------------------------------------------------------


Animations

CSS animations with @keyframes aren't scoped to a single component but you still don't want them to be global to avoid name collisions. This is why styled-components library exports a keyframes helper which will generate a unique instance that you can use throughout your app. This way we can keep the animation code close to core component.


import "./App.css";
import * as React from "react";
import styled,{keyframes} from "styled-components";


// Create the keyframes
const RotationAnimation = keyframes`
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
`;


const DivBox = styled.div`
  display: inline-block;
  width: 100px;
  height: 100px;
  background: red;
  animation: ${RotationAnimation} 2s linear infinite;
  &:hover {
    background-color: aqua;
  }
`;



export default function RotatingBox() {
  return(
      <div>
        <DivBox/>
      </div>
  )
}


---------------------------------------------------------------------------------------------------------------





Comments

Popular posts from this blog

React Js + React-Redux (part-2)

React Js + CSS Styling + React Router (part-1)

ViteJS (Module Bundlers, Build Tools)