Create a Switch in React as a Reusable Component

Danilo Rivera
2 min readDec 28, 2020

--

in some occasions this component can come with our framework in others not, many people will say “I can download a package to solve it”, but we can really solve it with custom code and customize it to our need.

For this solution we will use styled components. why?

  • Freddom to build custom components with css
  • No class policy
  • Server Side rendering
  • Sass and polished support

let’s start

first let’s install styled component
yarn add styled-components

we will use the following structure for the project

Switch Component

Now we will create the index for our switch in this case, we will use a container, to contain the label and the input type checkbox, then by props we will pass an id, color and a defaultValue.

id: each checkbox should have a unique id in this way the Virtual DOM can handle multiple checkox in a form

color: we will take advantage of styled components to be able to pass it the color we want and thus better fit the color palette of our project.

defaultValue: of course if it is a form we may need a default value, so we will pass it on here.

Now let’s add the style through the styled components, now a little parenthesis, if you are new to styled components, the way to use them is like when you call a component in react thanks to named exports, with name export you can have multiple named exports per file.

import { CheckBoxWrapper, CheckBox, CheckBoxLabel } from ‘./Style’;

in our case we call 3 different elements from our Style.js file

now I define these elements, in my style.js in this way:

we call the variable that will allow us to make use of all the power of styled component

import styled from ‘styled-components’;

then we create several constants that will represent our html elements and inside them we write an object with the css properties we want

export const CheckBoxWrapper = styled.div`
position: relative;
`;

I know is beautiful

Our component will look like the following

Final Result

Each switch is independent and we can customize the color we want.

Complete Code:

--

--

No responses yet