Mastering Styled Components with ease.

Styling the UI of a project is mostly a big deal for developers, especially when the developer has a lot of options at hand to choose from. Today we will be looking into Styled components, what it means, why we are choosing them, other options we can e…


This content originally appeared on DEV Community and was authored by Emmanuel Yusuf

Styling the UI of a project is mostly a big deal for developers, especially when the developer has a lot of options at hand to choose from. Today we will be looking into Styled components, what it means, why we are choosing them, other options we can explore and their best practices.

Outline

  • What is Styled-Component and why?
  • Features and benefits?
  • Things to explore in Styled components
  • Conclusion
  • Reference

Prerequisite

  • Basic understanding of react js
  • Basic understanding of CSS
  • Node installed on your PC
  • Terminal (CMD or other terminals)

What is Styled Components and Why?

Styled Components is a CSS-IN-JS styling solution for React and React Native, It uses tagged template literals which allows you to write plain CSS that is scoped to a single component inside your JavaScript code.

Styled-Components is a library that's adopted by numerous companies and is one of the most starred libraries in the React ecosystem.

Features and Benefits

  • Automatic Critical CSS: Styled components automatically keep track of which component is rendered on the screen and inject only their style, when combined with code splitting you will be loading the least amount of codes which helps your project performance.

  • No ClassName bugs: it generates unique class names for every style, you will never have to worry about duplications or misspellings.

  • Easier deletion of CSS: If you are working on a large project codebase that makes use of clean CSS files, it mostly becomes tricky to keep track of unused classes, but with styled-components, every style is tied to a specific component. If a component is not used, it can easily be pointed out which can easily be deleted by deleting the component.

  • Dynamic Styling: Just like React, where props are passed into components, sometimes styles need to be adapted based on props, styled components make this easy and simple.

  • Painless Maintenance: it is easy to organize styles with styled components, and you don’t have to move across different files to find the file affecting your component.

  • Automatic Vendor Prefixing: for some of the new css features you might have to write the css properties for each browsers, but with styled components you can write your css to the current standard and the library will handle the rest.

Things To Explore in Styled Components

  1. THEMING: with styled-components, you are given full support to theming which gives you the ability to create a theme or lay-down structure for the project style, theming mostly contains colors, sizes, fonts and other common things which will be used throughout the project to avoid repetition.

    To create a theme with styled-components, the Theme Provider wrapper needs to be imported.

import { ThemeProvider } from "styled-components"

This theme provider needs a theme object that will hold the CSS styling or value we want to apply to the styled components.

    const theme = {
      color: {
        primary: "#000f55",
        secondary: "#04043f",
        white: "#fff",
      },
      fontSize: {
        large: "2.5rem",
        medium: "1.5rem",
        small: ".785rem"
      }
    }

This is an example of what a theme value can look like, it can be expanded to suit your use cases.

Let's say we have components with these styles.

    const Button = styled.button`
        padding: 4px .7rem;
        color: ${props => props.theme.color.white};
        background: ${props => props.theme.color.primary};
        font-size: ${props => props.theme.fontSize.small};
        border-radius: 8px;
    `

    const FlexWrapper = styled.div`
        display: flex;
        align-items: center;
        justify-content: center;
    ` 

To use it, we need to wrap the ThemeProvider around all the projects which are mostly done on the App.js file.

    <ThemeProvider theme={theme}>
        <FlexWrapper>
            <Button>Click Please</Button>
        </FlexWrapper>
    </ThemeProvider>

Looking at the code above, ThemeProvider has been used to wrap all the components on the project, which passes the styling down to all the child components with ease.

2.Global Styles: Creating a style that serves as a universal style is one thing a lot of developers want to achieve, especially when there is a style that needs to be added to override some styles, Styled components make this easier to achieve to create a global style we have to create a file to store the style

Firstly, create a file name “globalStyles.js” and set it up using this format:

    import { createGlobalStyle } from "styled-components/macro"

    export default createGlobalStyle`
      * {
          margin: 0;
          padding: 0;
          box-sizing: border-box;
      }
    `

Looking at the code above, you can see that we are importing createGlobalStyle from the styled components which we are using to create the global style.

To use it, we have to import the component and add it to our App.js file:

    import GlobalStyles from "./globalStyles"

    function App() {
        return (
            <GlobalStyles />
            <AppContent />
        )
    }

3.Style Inheritance: Style Inheritance: Styled-component makes it possible to inherit styles from another styled component, which is simply done by passing it through the styled function.

    import styled from "styled-components"

    const Button = styled.button`
      padding: 4px 12px;
      border-radius: 4px;
      color: #fff;
      background: #000;
    `

Here is the button component, let create another variant of the component by inheriting some styles.

    const TransparentButton = styled(Button)`
      border: 1px solid #000;
      background: none;
      color: #000;
    `

The TransparentButton component will inherit all the styles from Button and update it with its own style.

4.Passing Props: Just like the regular react component that receives props to pass data, so as styles also need props to make the style dynamic, this is made possible with styled-components you can pass props through your styles.

The way styled-components handle their style is that it creates a React component that renders the HTML tags that correspond to the property in the styled object.

Let’s take, for example, we created a Button Component with this style:

    const Button = styled.button`
      padding: 4px 12px;
      border-radius: 4px;
      color: #fff;
      background: #000;
    `

In other to make it dynamic, we can set the background and color properties as props.

    const Button = styled.button`
      padding: 4px 12px;
      border-radius: 4px;
      color:${(props) => props.color ? props.color : '#fff'};
      background: ${(props) => props.bg ? props.bg : '#000'};
    `

Looking at this new structured component, the colour and background get the value of a prop, but if it’s not defined, it has been set to a default value, which has been achieved by creating a ternary condition as a check.

To use the component it will be structured like this

    <Button color="black" bg="orange">Clicked</Button>
    <Button>Click Me</Button>

5.Styling Regular Component: Another amazing thing about a styled component is that you can convert a React component into a styled component by just calling the styled() function and passing the component name inside, then the styling goes inside the string literal.

    function Button({props}) {
        return (
            <button className={props.className}>Click Me</button>
        )
    }

We want to convert the component to a styled component, we have a className attribute that has been passed as props to the component, in other to do this we will follow this process.

    Button = styled(Button)`
        padding: 4px 8px;
        border-radius: 4px;
        border: 1px solid #000;
    `

This will style the component with the styles from the string literal which will then be rendered with the component.

6.Use with other CSS frameworks: Styled components can work with all CSS frameworks without any issue, which helps you customize styles coming from other frameworks with ease without issue.

For example, let’s create an input component with Bootstrap styling:

    const Input = styled.input.attrs({
        className: "form-control"
    })`
        background: #fff
    `

We use the attrs method to add a class name attribute with the value form-control. This adds bootstrap styling to the component.

This also works for other CSS frameworks, Let's say we are using tailwind then we should have something like:

    const TailwindInput = styled.input.attrs({
        className: "
          mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md text-sm shadow-sm placeholder-gray-400
          focus:outline-none focus:border-sky-500 focus:ring-1 focus:ring-sky-500
          disabled:bg-gray-50 disabled:text-gray-500 disabled:border-gray-200 disabled:shadow-none
          invalid:border-pink-500 invalid:text-pink-600
          focus:invalid:border-pink-500 focus:invalid:ring-pink-500
        "
    })`
        background: #fff
    `

This code above works for tailwind just like the first one we talked about.

7.Special attributes: Adding Attributes to HTML tags is made possible with styled-components.

For example, let’s create a button component like this:

    const Button = styled.button`
        font-size: 0.75rem;
        font-weight: 700;
        padding: 8px 1.5rem;
        border: 1px solid green;
        color: green;
    `

Let's say we want to make it disabled, then we will need to introduce the disabled attribute which we can easily achieve by using the attrs method in styled-components.

    const Button = styled.button.attrs({
      disabled: true
    })`
        font-size: 0.75rem;
        font-weight: 700;
        padding: 8px 1.5rem;
        border: 1px solid green;
        color: green;
    `

Looking at the code above, we introduced this attrs method to the styled components which will help set the attribute disabled to true, which can come in handy probably, if we want to set the disabled value based on some conditions.

8.Switching Components types: Styled components dynamic nature helps a lot when it comes to changing the type of component you are rendering. Let’s take, for instance, you have a button component you may need to change to use as a link tag instead of the normal button tag, which you can follow this approach.

    const Button = styled.button`
        padding: 2px 5px;
        color: ${props => props.theme.color};
        border-radius: 3px;
    `

The button component will create and render the button element. we can easily change the render type when the component is been called by passing the “as” props to it with the type we want to use.

    <Button as="a">Go Back Home</Button>

This will render and create the component with the “a” tag element and apply every other thing from the component.

It can also be achieved by using the “withComponent” method.

     const Button = styled.button`
        padding: 2px 5px;
        color: ${props => props.theme.color};
        border-radius: 3px;
    `

    const Link = Button.withComponent("a")

The Link Component will render the anchor tag as a replica of the Button component, which is needed to avoid some level of duplication on the code base whereby one component can be used for different use cases.

Conclusion

Styled components have a lot of features that we can't touch in just one article, if you are interested in learning more about styled-components you can check the resources above out which can help understand the concept better.

Reference?

After looking at the tips above, you may find it interesting, but you don’t really get the concept of a styled component, or you are new to it, and you are willing to take some time to learn it, then I will be linking some resources here in which you can check out to get the needed knowledge to proceed with styled-components.


This content originally appeared on DEV Community and was authored by Emmanuel Yusuf


Print Share Comment Cite Upload Translate Updates
APA

Emmanuel Yusuf | Sciencx (2021-12-22T08:03:11+00:00) Mastering Styled Components with ease.. Retrieved from https://www.scien.cx/2021/12/22/mastering-styled-components-with-ease/

MLA
" » Mastering Styled Components with ease.." Emmanuel Yusuf | Sciencx - Wednesday December 22, 2021, https://www.scien.cx/2021/12/22/mastering-styled-components-with-ease/
HARVARD
Emmanuel Yusuf | Sciencx Wednesday December 22, 2021 » Mastering Styled Components with ease.., viewed ,<https://www.scien.cx/2021/12/22/mastering-styled-components-with-ease/>
VANCOUVER
Emmanuel Yusuf | Sciencx - » Mastering Styled Components with ease.. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/12/22/mastering-styled-components-with-ease/
CHICAGO
" » Mastering Styled Components with ease.." Emmanuel Yusuf | Sciencx - Accessed . https://www.scien.cx/2021/12/22/mastering-styled-components-with-ease/
IEEE
" » Mastering Styled Components with ease.." Emmanuel Yusuf | Sciencx [Online]. Available: https://www.scien.cx/2021/12/22/mastering-styled-components-with-ease/. [Accessed: ]
rf:citation
» Mastering Styled Components with ease. | Emmanuel Yusuf | Sciencx | https://www.scien.cx/2021/12/22/mastering-styled-components-with-ease/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.