Understanding Styled Components
Creating components in React is not complicated, but at the same time we have a difficulty in modeling the characteristics of these components, you must be confused with what I said now, right? But to answer that, just look at our Hello World where we had no trouble creating our component. Now let's dig deeper into the thing, suppose that in our application we had the following code:
const headerStyle = {
backgroundColor: 'red';
height: '40vh';
paddingBottom: '4rem';
paddingTop: '4rem';
width: '100%';
};
const logoStyle = {
fontSize: '16px',
textAlign: 'center'
};
<header style={divStyle}>
<h1 style={logoStyle}>My Logo</h1>
</header>
At first you might think that due to the size of this code, nothing would be harmed, right? But you are wrong, when we create our CSS inline together with the component we run the risk of filling our file with a sea of code, and this ends up harming the support of our application. Ok, we could also put these styles in an external file, but we would also go through possible problems regarding the support of each component and even in the separation of its characteristics and its children, it was thinking about these problems that Styled Components appeared.
Styled Components comes to simplify the way we work with each component, I mean: in its characteristics. To better understand how it works, let's get our hands dirty. Open the project folder we are developing on a terminal, then download the Styled Component package using the following command:
npm install --save styled-components
Now we will create a folder at the root of our project with the name of Components, right after we will create another folder inside the Components with the name of HelloWorld, once we can create a file named Style.js. To create our components, we first need to import the styled component, below how to import the styled component.
import styled from 'styled-components'
Now let's create our Hello World component with its features.
import styled from 'styled-components'
const HelloWorld = styled.h1`
color: #333;
font-family: arial;
font-size: 2.6rem;
`;
export { HelloWorld };
Very simple, right ?! But don't forget that to use it you need to import it into the page you want to place. Below is an example of the component in use.
import React from 'react';
import { HelloWorld } from './Components/HelloWorld/Style';
const App = () => {
return (
<>
<HelloWorld>Hello World!</HelloWorld>
</>
);
}
export default App;
Did you like what we did today? In the next post we will understand the use of props in our components, a big hug and until the next post :).
Top comments (0)