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 : 8405  
 
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 AND DEVELOPMENT.

 
 
 

Related Posts

New graphic window units - CSS

''Intercop 2022' is a project announced by Google, Microsoft, Apple and the Mozzilla Foundation to make all browsers offer the same web experience. The project has 15 focus areas and one…

How to upload files to the server using JavaScript

In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…

How to combine multiple objects in JavaScript

In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function.   How to copy objects with…

The Payment Request API: Revolutionizing Online Payments (Part 2)

In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features…

The Payment Request API: Revolutionizing Online Payments (Part 1)

The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

How do you stop JavaScript execution for a while: sleep()

A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…

Mastering array sorting in JavaScript: a guide to the sort() function

In this article, I will explain the usage and potential of the sort() function in JavaScript.   What does the sort() function do?   The sort() function allows you to sort the elements of…

Infinite scrolling with native JavaScript using the Fetch API

I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…

Sorting elements with SortableJS and storing them in localStorage

SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

Why shouldn't we use black?

Nowadays it is becoming more and more common for web pages to have the option to set them in dark mode, or to base their aesthetics directly on black or…

Clicky