Different ways to style in React Components.
Different ways to style in React Components.
React is an open-source library of JavaScript used to create user interfaces of single-page applications in both web and mobile. It is a framework that has a huge developer community.
Working with react we use components. Everything on React is component-based. These components are later rendered to show us the application.
To style these components of React there are several ways to do it. Some styling methods are the same as doing styling with a normal HTML file.
The ways to style in React Js components:
Inline styling
The method of inline styling has the same concept as we do in the HTML file. In React js we have inline styling too, but since we use JSX in react js the format for inline style is a bit different
In react js the inline styles are written as JavaScript objects. These objects can be created separately inside component like:
const styleBox = {
color: "white",
fontFamily: "Arial"
};
or even between the JSX like:
<h1 style={{backgroundColor: "lightblue"}}>Hello World!</h1>
There are few things we have to keep in mind. The attributes of style with two or more words should follow the format of camelCase. Writing inline style inside JSX should be between double curly brackets.
Normal CSS
The normal CSS is a common external styling technique that is also used for HTML files. We create an external CSS file for each component and do the required styling for them. The general process is to create same name CSS file as the name of the component file and use unique class names.
The above image is a CSS file and an example of normal CSS.
Styled Components
To create a styling under the variable name of JavaScript we use styled-components. The styled component is a third-party package or library which we need to install prior to using the format. To install we simply open up the terminal of that project file and type npm i styled-components.
To use styled-components in a component we first need to import it.
import styled from ‘styled-components’
then we write styled components like:
import styled from 'styled-components'
const CounterContainer= styled.div`
/* your css style here*/
`
const Paragraph = styled.p`
/* your css style here */
`
const Button = styled.button`
/* your css style here */
`
in the above example, we create tags or components of the following then define them later as styled components.
CSS modules
The concept of the CSS module is quite the same as a normal CSS external file, the key difference is that the written styling in the CSS module is only scoped till the mentioned component. To apply this we make a CSS file and the name of it has a specific format- nameOfComponent.module.css. This CSS file then is to be imported to its respective component file.
Its main advantage is to use the class's name without worrying it get conflicted with other CSS files.