React and CSS Tutorial

In this tutorial, you will learn how to use CSS in React to styling your applications.

Styling in React

  1. Styling is a crucial aspect of web development.
  2. In React, you can style your components using various methods, including CSS, CSS-in-JS, and CSS frameworks like Bootstrap.

Inline Styles

  1. React allows you to define inline styles directly in your components.
  2. Styles are defined as JavaScript objects, making it easy to set dynamic styles.
const MyComponent = () => {
    const textStyle = {
      color: 'blue',
      fontSize: '16px',
    };
  
    return <p style={textStyle}>Styled Text</p>;
  };
  

Using CSS Classes

  1. You can apply CSS classes to React components to separate styling from logic.
  2. Create a CSS file and import it in your component file.
    1. // MyComponent.js
      import './MyComponent.css';
      
      const MyComponent = () => {
          return <div className="styled-div">Styled Div</div>;
      };
      
      /* MyComponent.css */
      .styled-div {
          color: red;
          font-size: 18px;
      }
          

      CSS Modules

      1. CSS Modules provide local scoping for your CSS classes, avoiding naming conflicts.
      2. Create a CSS file with the ".module.css" extension.
      // MyComponent.module.css
      .myComponent {
          color: green;
          font-size: 20px;
      }
      
      // MyComponent.js
      import styles from './MyComponent.module.css';
      
      const MyComponent = () => {
          return <div className={styles.myComponent}>Styled with CSS Modules</div>;
      };
          

      CSS-in-JS

      1. Libraries like styled-components and Emotion allow you to write CSS as JavaScript.
      2. Define styled components with tagged template literals.
      import styled from 'styled-components';
      
      const StyledButton = styled.button`
          background-color: #007bff;
          color: white;
          border: none;
      `;
      
      const MyComponent = () => {
          return <StyledButton>Styled Button</StyledButton>;
      };
          

      Importing Style Sheet

      1. We can use our own style sheet as we usually done for the HTML Files
      2. If you are only importing a single CSS file, then either method is fine.
      3. However, if you are importing multiple CSS files, or if you are using a CSS preprocessor such as Sass or LESS, then it is recommended to use the import statement. This will help to keep your code more modular and organized.
      import React from "react";
      import styles from "./styles.css";
      
      const MyComponent = () => {
          return (
          <iv className={styles.container}>
              <h1>Hello, world!</h1>
          </div>
          );
      };
      
      export default MyComponent;