How to use styled-components
Tags: styledcomponents, react, webdev, css
Published: 2019-01-05 09:59:41

---
title: How to use styled-components
published: true
description: Quick tutorial to start using styled-components
tags: styled-components, react, webdev, css
---


Libraries i used for this mini project:

1. Styled-Components
2. Create-React-App

if you want to use CSS-in-JS and you don't know how to use styled-components with React i hope you will get enough knowledge of basics to start using it.
we will learn by creating a simple LoginIn form (without validation stuff) using style components in CRA.

Lets start with installation:
open your terminal and write:
<pre>npm install --save -g styled-components </pre>
----------------------------------------------------------------------------------
Here is our first example of an variable div that will display label and input in CRA:
fileName: StyledForm.jsx


<pre>
import styled from "styled-components"

 //now below style a parent div as a variable and name it 
 //Note: always use Pascal Case for Naming Styled Components
 //we use styled.variableType to create a variable 

const ParentForm = styled.form`
  display: grid;
  grid-template-columns;1fr;
  grid-template-rows:auto;
    border: 1px solid Black;
    margin: auto;
    *{
      margin: auto;
      padding: 0.5rem 1rem;
      display:grid
    }

`;

// don't export default anything from styled components file

export {ParentForm}
</pre>

Alright here we created our first styled variable that is Parent div for the Signin form.


----------------------------------------------------------------------------------
Lets now create main Form component.

Filename: Form.jsx

<pre>
import React from "react";

//create a stateful class

class Form extends React.Component {}
</pre>

Now we import ParentForm we created in StyledForm.jsx.

<pre>
import React from "react";import {
  ParentForm
} from "../StyledForm.jsx";


//create a stateful class

class Form extends React.Component {}
</pre>

now we will create a render function in that we will return this component.
----------------------------------------------------------------------------------


<pre>
import React from "react";import {
  ParentForm
} from "../StyledForm.jsx";


//create a stateful class

class Form extends React.Component {
render(){
return <ParentForm>Here we will add form labels and inputs </ParentForm>
}
}
</pre>

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


But wait what if you have to add same template n number of times ?
for efficiency we will create a function that will take all the elements of form 
as an argument and return us the template html.

<pre>
import React from "react";import {
  ParentForm
} from "../StyledForm.jsx";


//create a stateful class

class Form extends React.Component {
render(){  
const functionalDiv = (id, type, placeHolder) => {
      return (
        <div>
          <label htmlFor={id}>{id}</label>
          <input
            type={type}
            name={id}
            id={id}
            placeholder={placeHolder}
            required
          />
        </div>
      );
    };
return <ParentForm>Here we will add form labels and inputs </ParentForm>
}
}
</pre>

----------------------------------------------------------------------------------
now lets add our rest of components:

<pre>
import React from "react";
import {
  ParentForm
} from "../StyledForm.jsx";


//create a stateful class

class Form extends React.Component {
render(){  
const functionalDiv = (id, type, placeHolder) => {
      return (
        <div>
          <label htmlFor={id}>{id}</label>
          <input
            type={type}
            name={id}
            id={id}
            placeholder={placeHolder}
            required
          />
        </div>
      );
    };
return (
    <>
        <ParentForm >
          <div>
            <p>Please SignIn to Access Your Account.</p>
          </div>
          {functionalDiv("username", "text", "enter username")}
          {functionalDiv("password", "password", "enter password")}
          <div>
            <StyleButton
              bgcolor="black"
              type="submit"
              value="submit"
              onClick={_ => alert("Successfully Logged in ")}
            >
              Submit
            </StyleButton>
          </div>
        </ParentForm>
      </>

)
}
}
</pre>

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

Now create an onSubmit Stylebutton that will prevent the whole page from refreshing.
<pre>
const onSubmit=e=>{
e.preventDefault()
}</pre>


Now we will create the remaining styling for the form and export them.
<pre>
import styled from "styled-components";
const ParentForm = styled.form`
  display: grid;
  grid-template-columns;1fr;
  grid-template-rows:auto;
    border: 1px solid Black;
    margin: auto;
    *{
      margin: auto;
      padding: 0.5rem 1rem;
      display:grid
    }

`;
const HeaderForm = styled.div`
  > p {
    font-size: 1.5em;
    font-weight: 600;
  }
`;
const FormMainBody = styled.div`
  grid-template-columns: 1fr;
  grid-template-rows: 1fr 1fr;
  margin: auto;
  label {
    text-align: left;
    text-transform: uppercase;
    font-weight: 600;
  }
  input {
    border: 1px solid Black;
    padding: 5px 10px;
    caret-color: green;
  }
`;
const StyleButton = styled.Stylebutton`
  padding: 5px 20px;
  color: white;
  background-color: ${props => [props.bgcolor]};
`;

export { ParentForm, HeaderForm, FormMainBody, StyleButton };
</pre>

----------------------------------------------------------------------------------
Here is the final Form.js file:
<pre>
import React from "react";
import {
  ParentForm,
  HeaderForm,
  FormMainBody,
  StyleButton
} from "../StyledForm.jsx";

class Form extends React.Component {
  render() {
    const functionalDiv = (id, type, placeHolder) => {
      return (
        <FormMainBody>
          <label htmlFor={id}>{id}</label>
          <input
            type={type}
            name={id}
            id={id}
            placeholder={placeHolder}
            required
          />
        </FormMainBody>
      );
    };
    const onSubmit = e => {
      e.preventDefault();
    };
    return (
      
        <ParentForm onSumbit={onSubmit}>
          <HeaderForm>
            <p>Please SignIn to Access Your Account.</p>
          </HeaderForm>
          {functionalDiv("username", "text", "enter username")}
          {functionalDiv("password", "password", "enter password")}
          <div>
            <StyleButton
              bgcolor="black"
              type="submit"
              value="submit"
              onClick={_ => alert("Successfully Logged in ")}
            >
              Submit
            </StyleButton>
          </div>
        </ParentForm>
     
    );
  }
}
export default Form;

</pre>
----------------------------------------------------------------------------------
That's it that's how we created a simple login in form using styled-components.
here is the codesandbox link :<a href="https://codesandbox.io/embed/6zo26xvv43">here</a>
If you get any questions regarding this DM me on Twitter.