We all know how hard it is to create customizable Apps or Websites UI components, through my career I've always struggled with creating generic components which could be reusable and easily customizable.
Until I find styled-components 🤩, It's a react library that makes reusability looks easy. It allows you "write CSS" into javascript and create customizable components that can be used across your application without stress.
Differently from CSS classes, styled-components concentrate all the logic within a unique component, instead of pilling up classes you can easily pass props that change the appearance of your component, here is an example of how it can simplify your life
<!DOCTYPE html>
<html>
<head>
<style>
.my-button {
background-color: orange;
padding: 10px 30px;
font-size: 18px;
border: 0;
margin: 2px;
}
.my-secondary-button {
background-color: gray;
}
</style>
</head>
<body>
<button class="my-button">I'm the primary button</button>
<button class="my-button my-secondary-button">I'm the the secondary button</button>
</body>
</html>
import React from 'react';
import { render } from 'react-dom';
import styled from 'styled-components';
const Button = styled.button(({ isPrimary }) => ({
backgroundColor: isPrimary ? 'orange' : 'gray',
padding: '10px 30px',
fontSize: '18px',
border: 0,
margin: 2
}))
const App = () => (
<>
<Button isPrimary>Something Goes Here</Button>
<Button>Something Goes Here</Button>
</>
);
render(<App />, document.getElementById('root'));
Here at Two of Us Tech, we use the styled-components theming feature, which allows us to define a set of variables like margin, padding, and colors and access it within our components. It gives us the ability to speed up our development process and keep all variables within the theme as the only source of truth avoiding inconsistency between different components.
import { ThemeProvider } from "styled-components"
const theme = {
fg: "red",
bg: "white"
};
// The "theme" object is injected into styled components props
const Button = styled.button(({ theme }) => ({
color: theme.fg,
border: 0,
background: theme.bg,
}))
return (
<ThemeProvider theme={theme}>
<Button>Customized Button </Button>
</ThemeProvider>
)
At the end of the day, you should consider various factors before choosing a CSS-like framework, such as the learning curve, project size, team capacity, and much more. To learn more about styled-components we recommend you check their documentation here.