Introduction
React supports four types of options to style components.
CSS Stylesheet
You can simply define CSS into a separate file and then you just need to import in the component file. You can even create a separate component file rather than merging all CSS into one.
When a React application is made of complex CSS Modules or regular, CSS stylesheets is recommended.
- .container {
- margin: 40px;
- border: 5px dotted pink;
- }
-
- .center {
- font-size: 15px;
- text-align: center;
- }
- import React from 'react';
- import './style.css';
-
- const App = () => (
- <div className="container">
- <p className="center">Get started with CSS styling</p>
- </div>
- );
-
- export default App;
A CSS Module is a CSS file with all class names and animation names are scoped locally.
We import the CSS file
import styles './style.css'
- :local(.container) {
- margin: 40px;
- border: 5px dashed pink;
- }
- :local(.center) {
- font-size: 15px;
- text-align: center;
- }
- :local(.className) - you can use create-react-app because of webpack configurations
- .className - you use your own react boilerplate.
- import React from 'react';
- import styles from './style.css';
-
- const App = () => (
- <div className={styles.container}>
- <p className={styles.center}>Getting started with CSS styling</p>
- </div>
- );
-
- export default App;
In case you're configured with webconfig.js file, then you can add below code into webconfig file so that it handles the styling of your local component.
- {
- test: /\.css$/,
- loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
- }
Inline styling
As the name suggests, in a React application, it's not similar to HTML inline styling string. In the React app, the styling property is not similar to a simple CSS property, we need to define it in camelcase.
- import React from 'react';
-
- const divStyle = {
- margin: '10px',
- border: '2px solid pink'
- };
- const pStyle = {
- fontSize: '15px',
- textAlign: 'center'
- };
-
- const Dialog = () => (
- <div style={divStyle}>
- <p style={pStyle}>Configured inline style</p>
- </div>
- );
-
- export default Dialog;
Styled-components
Styled-components is a component-level style that is a combination of JavaScript and CSS.
To use this library, we need to install the package first.
- npm install styled-components --save or yarn add styled-components
To use Style-component, please see the below snippet.
- import React from 'react';
- import styled from 'styled-components';
-
- const Div = styled.div`
- margin: 20px;
- border: 2px outset pink;
- &:hover {
- background-color: green;
- }
- `;
-
- const Paragraph = styled.p`
- font-size: 10px;
- text-align: center;
- `;
-
- const DialogBox = () => (
- <Div>
- <Paragraph>Styling with styled-components</Paragraph>
- </Div>
- );
-
- export default DialogBox;
Summary
All these were ways of styling React components. You can choose any of the options based on your requirements and preferences.