Styling React Components: Recommendations and Suggestions

by Janeth Kent Date: 17-05-2020 javascript React CSS tips

With CSS we can set the presentation of a document through the rules that control the formatting of an element on a web page. Using CSS techniques, we can make web pages more attractive and elegant.

Before going into the topic of posting, let's talk about React.

By now, almost everyone knows that it is a powerful JavaScript library for creating user interfaces.

In practice, it manages the level of visualization of the application. The best part is that it allows you to split a component into smaller, reusable components.

Instead of putting all the logic into a single file, writing smaller components has a better advantage. By writing well encapsulated components, we are essentially creating a testable application with good separation of concerns and maximum reuse of code..

There are many ways to customize the React component, these are the common ones:

Inline CSS
CSS Style Sheet
CSS modules

We will not go into details and differences between them as this depends mainly on the case of use and the type of application. Everything depends on your individual preferences and your application's specific complexity.

If you only want to add a few style features, the best choice is inline styling.

The style-component is ideal if you want to reuse your style attributes in the same file.

We suggest CSS modules or CSS stylesheets if your application is more complex.

1. CSS Stylesheet

import React from 'react';  
import './DottedBox.css';    
const DottedBox = () => (    

Get started with CSS styling

); export default DottedBox;

You just have to import './DottedBox.css' so you can use a separate css file for each component

.DottedBox {
margin: 40px;
border: 5px dotted pink;
.DottedBox_content {
font-size: 15px;
text-align: center;

2. Inline styling

Inline CSS means defining the properties of CSS by using a style attribute with an HTML tag or by adding styles directly on the desired element. Using HTML, we assign a string value to the style attribute. This string contains several CSS properties; each property will be separated from the other by a semicolon. For an example of a simple "Hello World" page formatted is shown below:

< !DOCTYPE html >  
< html >    
< head >      
< title >Inline CSS
< /title >    
< /head >    
< body >      
< p style=" font-size: 20px; color:#4a54f1; 
text-align:center; padding-top:100px; " >        
Hello World!!!      
< /p >    
< /body >  
< /html >

In React, inline styles are not specified as a string. Instead, they are indicated with an object whose key is the camelCased version of the style name, and whose value is the value of the style, usually a string.

For example: margin-top -> marginTop , border-radius -> borderRadius , font-weight -> fontWeight , background-color -> backgroundColor.

The main steps to defining CSS online are listed below:

1. Change the name of the CSS property in its camelCase version as "background-color" to "backgroundColor", "font-size" to "fontSize", etc..

2. Create an object with all CSS properties as keys and their CSS values.

3. Assign that object to the style attribute.

Here's an example:

import React from 'react';   
const divStyle = {    
margin: '40px',    
border: '5px solid pink'  
const pStyle = {    
fontSize: '15px',    
textAlign: 'center'  
const Box = () => (    

Get started with inline style

); export default Box;

What are the disadvantages of online CSS?

1. CSS properties that duplicate each other

2. The properties of CSS will be limited to the scope of a single component, so they cannot be reused in any way.

3 We won't be able to use all the power of CSS, for example, no pseudo-classes, pseudo-elements, media requests, keyframe animations, etc., to the full.

3. It is difficult to maintain or modify/update, and many online CSSs can reduce code readability.

4. Prevents performance, the style object will be recalculated each time it is redrawn.

3. CSS Modules

A CSS Module is a CSS file in which all class and animation names are grouped and displayed locally by default.

import React from 'react';  
import styles from './DashedBox.css';    
const DashedBox = () => (    

Get started with CSS Modules style

); export default DashedBox;

  • Similar to css you have to import css file import styles './DashedBox.css'
  • then you can access to className as you access to object

:local(.container) {
margin: 40px;
border: 5px dashed pink;
:local(.content) {
font-size: 15px;
text-align: center;

local(.className) use it when implementing the create-react-app application with webpack configurations

.className use this if you are using your own react boilerplate.

To make CSS modules run on Webpack you only need to include the above modules and add the following loader to your webpack.config.js file:

. . .
test: /.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' 
. . .

4. Styled-components 

Styled-components is a library for React and React Native that allows you to use component-level styles in your application that are composed of a set of JavaScript and CSS.


import React from 'react';  
import styled from 'styled-components';    
const Div = styled.div`    
margin: 40px;   
border: 5px outset pink;      
&:hover { background-color: yellow;   
const Paragraph = styled.p`    
font-size: 15px;    
text-align: center;  
const OutsetBox = () = > (    
< Div >      
< Paragraph >Get started with styled-components  
< / Paragraph >   
< / Div >  
export default OutsetBox;

  • First we need to install styled-components library
  • npm install styled-components --save
  • Now we can create a variable by selecting a particular html element where we store our style keys const Div = styled.htmlElemnet`color: pink`
  • Then we use the name of our variable as a wrapper  < Div > < / Div > kind of react component:)
  • Tips to use emoji icons key shortcut CTRL+CMD+SPACE

As mentioned at the beginning of the post, all these ways of styling React components have their advantages and disadvantages.

We suggest you try them all!


All Examples from Agata Krzywda @aghh1504

People vector created by freepik -

by Janeth Kent Date: 17-05-2020 javascript React CSS tips hits : 4326  
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.


Related Posts

How To Add Filter Effects to Images with CSS

To achieve interesting effects on your images, learn about the 'filter' and 'Backdrop-Filter' properties of CSS. CSS filters are a very attractive feature of CSS that allows you to apply certain…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The package managers npm and yarn: main differences

Npm and yarn are package managers that help to manage a project’s dependencies. A dependency is, as it sounds, something that a project depends on, a piece of code that…

The Javascript asign() method to merge and clone objects

In this article, we will be covering Object.assign()method in javascript in detail with examples. A javascript object is a collection of key-value pairs. Keys are also known as properties of object. Keys…

All the javascript functions and methods to manipulate arrays

This article will show that the prominent JavaScript array functions are .map(), .filter(), and .reduce(), and will then go through examples of instances in which .every() and .some() would save…

TypeScript: The evolution of JavaScript

When you're involved in the development of a large project, programming languages like JavaScript don't seem to be the best solution. Their lack of elements such as Language Aids has…

Awesome JavaScript Games and Js Software to create Games

Best sites js13kGames 2019 - Highlights from the js13kGames 2019 competition. js13kGames 2018 - 13 Games in ≤ 13kB of JavaScript. js13kGames 2017 - Build a game in 13kB or less with js13kGames. Adventure Triangle:…

Is JavaScript good for machine learning?

One of the things you always hear when you are talking to someone related to the M.L. world is that, one must learn Python because the vast majority of the…

Introduction to BEM (Block Element Modifier)

Problems with naming CSS classes I think I might not be the only one with this experience: after finally grasping all the important concepts regarding CSS I wanted to start giving…

First steps into JavaScript – a practical guide 3

After we learned the basic ofaccessing DOM elementsandhow to modify them,we are ready for the more exciting parts – handling DOM events. This allows us to make our web way more…

JavaScript: Promises explained with simple real life examples

Handling asynchronous data flows is complex, who hasn't faced codes like this one?: checkWeather('palma de mallorca', (error, weather) => { if (error) throw error; if (weather === 'well') { return checkFlights('palma…