Styling And CSS In React

Introduction

 
In the previous article, we learned about condition rendering and list rendering in React and saw in how many ways, we can use conditional rendering. We made the use of Array.Map() in list rendering. Now, in this article, we will learn about Styles and CSS basics in React and how styled components work in React.
 

Styling in React

 
There are 4 ways styling can be done in React.
  • CSS Stylesheets
  • Inline style
  • CSS Modules.
  • CSS in JS libraries.
To specify the CSS class, we can use the className attribute. This will apply to all DOM and SVG elements.
 

CSS Stylesheets

 
This styling involves importing external CSS file in our component. This is used in the same way as we use in our HTML form. Using this approach, we can create individual file for each component.
 
For example,
 
I have created a file named custom.css having the below code
  1. .error{  
  2. color:red  
  3. }  
  4.   
  5. .info{  
  6. colorblue  
  7. }  
Now, import the css file in your component file
  1. import React from 'react';  
  2. import '../css/custom.css';  
  3.   
  4. const Messages = () =>(  
  5.        <div>  
  6.               <p className="error">This is Error</p>  
  7.               <p className="info">This is information</p>  
  8.        </div>  
  9. )  
  10. export default Messages;  
This will display an output.
 
Styling And CSS In React
 

Inline style

 
This styling is not a string. It contains a key-value pair in camel case format having style name and its value. The value is usually a string.
In this, we can use style={nameofvariable} as to pass variable name created or directly style is passed style={{color:’red’}}
 
For example,
 
In our component, we will define an object containing style key-value pair
  1. import React from 'react';  
  2. const error ={  
  3.     color: 'red',  
  4.     fontWeight:'bold',  
  5.     fontSize:'14'  
  6. }  
  7.   
  8. const info ={  
  9.     color: 'blue',  
  10.     fontWeight:'italics',  
  11.     fontSize:'16'  
  12. }  
  13.   
  14. const Messages = () =>(  
  15.     <div>  
  16.         <p style={error}>This is Error</p>  
  17.         <p style={info}>This is information</p>  
  18.     </div>  
  19. )  
  20.   
  21. export default Messages;  
The output will be displayed as below.
 
Styling And CSS In React
 

CSS Modules

 
In a class module, every class name and animation are scoped locally to the component that is importing it. In this way, a naming convention can be used based on requirements without worrying about global conflicts as React uses component and every component is separate until imported.
 
For example,
 
custom.css
  1. .error {  
  2.    color:red;  
  3.    font-weightbold;  
  4.    font-Size :14  
  5. }  
  6.   
  7. .info{  
  8.    colorblue;  
  9.    font-weight:'italics';  
  10.    font-size:'16';  
  11. }  
And in style component,
  1. import React from 'react';  
  2. import styles from '../css/custom.css';  
  3. class Messages extends React.Component{   
  4.      render(){   
  5.           return(  
  6.                <div>  
  7.                     <p className={styles.error}>This is Error</p>   
  8.                </div>  
  9.           )  
  10.      }  
  11. }  
  12. export default Messages;  
This will display an output as below.
 
Styling And CSS In React
 
As in the above snapshot, we can see that CSS is not applied, the reason is for using CSS Modules concept in React the naming convention for CSS files should be <ModuleName>.module.css
 
Now change the file name as Messages.module.css and update its import name in Messages.js file. Now the output will be displayed as below:
 
Styling And CSS In React
 
CSS Modules allows class composition as one class can be inherited in other class. It is also possible to extend multiple classes at the same time. This feature allows using existing classes with a new class.
 

Css-In-Js (styled component)

 
Styled components are Css-In-Js library that includes the utilization of template literals to style your desired component. This technique is used for writing CSS code to customize your component and it will also not conflict with other elements or components.
 

Benefits of Styled Component

 
Automatic critical CSS -The styles component keeps track of components rendered on the page and add their styles and will do nothing else, that results in making it fully automatic.
 
Conditional Rendering -The styled component has the functionality to implement styles based on values of props which is not provided by any other CSS methods like SASS, LESS, etc.
 
Easy Maintenance -The styled components provide quick changes as we need not surf all the CSS files in search of CSS or if it may affect other components as it is implemented component-wise.
 
No Confliction of classes - There is no conflict of the class name in the styled component as each style is bound to its component and generates a unique class name.
 
For using Styled Component, we need to execute below 2 steps
 
First, to use styled component first install styled-components through npm manager using the command given below.
  1. npm i styled-components  
Now, the second thing. We need to import our styled component in our component.
  1. import styled, { css } from 'styled-components';  
After completing the above 2 steps, we can continue using style components.
 
Let’s see a demo for Styled Components
 
Created one component file named UserForm.js
  1. import React,{Component} from 'react';  
  2. import styled from 'styled-components';  
  3.   
  4. const Textarea = styled.textarea`  
  5.          padding: 10px 5px;  
  6.          background-color:black;  
  7.          color:white;  
  8. `;  
  9.   
  10. const Button = styled.button`  
  11.          padding: 5px;  
  12.          color : black;  
  13.          background-color: gray  
  14. `  
  15. const Label = styled.label`  
  16.          color : black;   
  17.          background-color: yellow  
  18. `  
  19.   
  20. class UserForm extends Component{  
  21.          render(){  
  22.                   return(  
  23.                            <div>  
  24.                                     <Label>Enter Name</Label>  
  25.                                     <Textarea type="text"></Textarea>  
  26.                                     <Button type="submit">Submit</Button>  
  27.                            </div>  
  28.                   )  
  29.          }  
  30. }  
  31.   
  32. export default UserForm;  
Now import that form in App.js file
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import UserForm from "./components/UserForm";  
  5.   
  6. function App() {  
  7.        return (  
  8.               <div className="App">  
  9.                      <header>  
  10.                             <img src={logo} className="App-logo" alt="logo" />   
  11.                      </header>  
  12.                      <UserForm></UserForm>  
  13.               </div>  
  14.        );  
  15. }  
  16.   
  17. export default App;  
This will display output as below,
 
Styling And CSS In React
 
FAQ related to Styling and CSS in React,
 

How CSS classes can be added in the component in React?

 
In React, we can pass prop as className to the element to define CSS class in camelCase.
  1. <p className=”error”>Error</p>  
Can inline styles be used in a React component? Which technique is better to use in component?
 
Yes, Inline styles can be used in React. But using inline styles is not preferable to React. Using CSS class is better in terms of performance rather than inline styles.
  

Which browsers support styled components?

 
Styled Components are supported by,
  • V2.x (React v0.14+): IE9, Chrome, Edge.
  • V3.x (React v0.14+): IE9+,Chrome, Edge.
  • V4.x (React v16.3+): IE11, IE9, Chrome, Edge.
Chrome and edge are referred to as Evergreen browsers as they can be updated without depending on the operating system on which it is needed to install.
 

Why should styled components not be declared in render() method?

 
While declaring styled component in render() method of the component,  React will recompile that part of DOM subtree on each render instead of just observing the changes of the previous node. This will result in performance and behavioral issues. So, it is preferred to use a styled component above your component definition. 
 
Example:
 
The below code should not be used as each time component is rendered without considering only changes.
  1. const User = () => {  
  2.     const Button = `  
  3.         color: black;  
  4.         background-color: white;  
  5.     `  
  6.   
  7.     return(  
  8.         <div>  
  9.             <button>Click Me</Button>  
  10.         </div>  
  11.     )  
  12. }  
We can use the below code which will improve performance and will only check for changes that have been done.
  1. const Button = `  
  2.       color: black;  
  3.       background-color: white;  
  4. `  
  5.   
  6. const User = () => {  
  7.       return(  
  8.             <div>  
  9.                   <button>Click Me</Button>  
  10.             </div>  
  11.       )  
  12. }  

Basics of Form in React

 
HTML form elements work a little bit differently than they do in React. This is because the form element has some internal state. This form behavior has the default HTML behavior of submitting to a new page when the user submits the form. This same concept will also work in React but sometimes it will fail so it is preferable to use JavaScript function to access submitted data. This can be achieved using a technique called “Controlled Components”.
 

Conclusion

 
In this article, we reviewed some basics Styles and CSS and how it can be used in React and some basic implementation of Styled Components and CSS Modules. In the next article, we are going to learn about the details of Form and how it can be used in React and Component of Lifecycle methods.
 
Next in this series > Forms in React 
Author
Priyanka Jain
0 9.6k 894.8k
Next » Forms In React