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 : 4640  
 
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

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

A FULFILLED PROMISE - Using the FETCH API to make AJAX calls

In this article we talked about what AJAX calls are and how to use them in a traditional way, by using the XMLHttpRequest (XHR) object. In short, thanks to AJAX…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

The easiest way to align items using flexbox

With the release of flexbox in CSS, it has become an essential tool when placing elements next to each other, since, by default, the children of a display: flexare stacked…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

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…

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