Introduction to React Styled Components
In React.js world there are many options when it comes down to “how do I style my React application?”, in this post we will discuss the option “Styled Components”.
Styled Components?
Basically this is a way of writing CSS inside Javascript, but what makes it different is the way we can implement the styling for each components, this is an example of how it works:
The first thing you need to do is install styled-components, you can do it with NPM or Yarn
# with npmnpm install --save styled-components# with yarnyarn add styled-components
Now you can use styled-components inside your React application, in this example we are going to create a simple ButtonComponent. If you ever used Material UI, you will find yourself coding similar stuff, but in case you are new to this, you will need to import this:
import styled from 'styled-components'
then, using this syntax you will create the Button
const Button = styled.button`padding: 10px 30px;background: honeydew;`;
And that’s it! The way you will call this component inside your applications is similar to this
function App() { return ( <> <Button>Click me</Button> </> );}
As you can see, things are pretty much normal CSS when creating a Components, but what I want to discuss now it the following topic: Why? Why do we need to do this and what is the benefit of using this type of tools for styling?
One thing you can do using styled-components it’s adapting based of props, in the getting started page it says:
You can also extend styles, use theming (something you can see here), and many more things!
Here is a simple Repl.it already set with styled-components for you to play!
https://replit.com/@RobertoMoreno2/Introduction-to-React-Styled-Components#src/App.jsx