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
CSS in JS

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!

Enjoy!

All Examples from Agata Krzywda @aghh1504

People vector created by freepik - www.freepik.com

 
by Janeth Kent Date: 17-05-2020 javascript React CSS tips hits : 5557  
 
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 use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

How to use the charCodeAt method in JavaScript

The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method. The charCodeAt method…

How to use the charAt method in JavaScript

The charAt method is accepted by strings in JavaScript, returning the position of the character passed as a parameter within the string. If the string contains multiple occurrences of the character…

Strings in JavaScript: What they are and how to use them

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in…

Dates in local format with Javascript

In the articles we have about dates in JavaScript we were missing one about how to create dates in local format with JavaScript. That is to say, being able to…

Formatting hours in Javascript

Continuing with the set of articles that talk about internationalisation elements, like the previous one where we talked about relative dates in JavaScript, we will see in this one how…

Request data with prompt in JavaScript

After having published several articles about how to manipulate arrays and dates, today I will publish a post that some of you will find too basic and others will find…

Relative dates in JavaScript

One of the interesting things about the internationalisation library represented in the Int object is the handling of relative dates in Javascript. This handling allows us to represent a date…

How to access webcam and grab an image using HTML5 and Javascript

We often use webcams to broadcast video in real time via our computer. This broadcast can be viewed, saved and even shared via the Internet. As a rule, we need…

The JavaScript forEach loop

We have already talked about how to handle some of loops  types in Javascript including for, for-in and for-off loops. In the case of today we are going to see how…

What are React Hooks and what problems they solve

Working with React, - and before the release of Hooks in version 16.8 -  there was always the possibility to create components in three different ways based on a number of…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration