React JS - Fundamentals

Introduction to React JS

Β·

12 min read

React JS - Fundamentals

React Introduction

Create React App

  1. Without any tools

To use React directly in an HTML file without any build tools like Webpack, Vite, or Create React App, you can leverage the React and ReactDOM libraries via a CDN. This simple, lightweight approach works for small projects or demos.

Set Up an HTML and JavaScript

Create a basic HTML file that includes the React and ReactDOM libraries via CDN. Then, you can write your React code directly in a <script> tag using JSX.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>React Without Build Tools</title>
  <!-- React and ReactDOM via CDN -->
  <script src="https://unpkg.com/react@18/umd/react.development.js" 
    crossorigin></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"
     crossorigin></script>
  <!-- Babel for JSX transpiling in the browser -->
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>

  <!-- React code -->
  <script type="text/babel">
    // Simple React Component
    function App() {
      return (
        <div>
          <h1>Hello, React!</h1>
          <p>This is a React app without using build tools 
            like Webpack or Create React App.</p>
        </div>
      );
    }

    // Render the App component into the root div
    ReactDOM.render(<App />, document.getElementById('root'));
  </script>
</body>
</html>

Explanation:

  1. React and ReactDOM via CDN: The script tags pointing to the react.development.js and react-dom.development.js files load React and ReactDOM into the browser. These files are the development versions and should not be used in production (use the minified versions for production).

  2. Babel via CDN: The babel.min.js script is included so the browser can transpile JSX into regular JavaScript. Without a bundler like Webpack, Babel will run in the browser to compile JSX. Note that this is also meant for development, not production.

  3. React Code: Inside the <script> tag with type="text/babel", we write the React code. Babel transpiles this JSX into JavaScript, which is then rendered by ReactDOM into the #root div.

  4. Create React App

To create a React app using Create React App (CRA), you can follow these steps. Create React App is a great tool that sets up a new React project with all the necessary configurations for Webpack, Babel, ESLint, and other essential tools for modern web development, without needing to configure them manually.

Step 1: Install Node.js and npm

Before proceeding, make sure you have Node.js and npm installed. You can check by running:

node -v
npm -v

If not installed, download Node.js from https://nodejs.org/.

Step 2: Create a React App

Use the following command to create a new React app with Create React App:

npx create-react-app my-app
  • npx is a package runner tool that comes with npm 5.2+ and higher. It allows you to run packages without having to install them globally.

  • create-react-app is the command to create a new React app.

  • my-app is the name of your project (you can replace my-app with any name you prefer).

After running the command, Create React App will automatically set up your project directory with all the necessary files and dependencies.

Step 3: Navigate to Your Project Directory

Once the setup is complete, navigate to the project directory:

cd my-app

Step 4: Start the Development Server

To start the development server, run:

npm start

This will start a local development server and open your React app in the browser at http://localhost:3000/. The development server will automatically reload the page whenever you make changes to your code.

Step 5: Explore the Project Structure

Create React App will generate a default project structure like this:

my-app/
β”œβ”€β”€ node_modules/
β”œβ”€β”€ public/
β”‚   β”œβ”€β”€ index.html
β”‚   └── favicon.ico
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ App.js
β”‚   β”œβ”€β”€ App.css
β”‚   β”œβ”€β”€ App.test.js
β”‚   β”œβ”€β”€ index.js
β”‚   β”œβ”€β”€ index.css
β”‚   └── logo.svg
β”œβ”€β”€ .gitignore
β”œβ”€β”€ package.json
└── README.md
  • public/index.html: The main HTML file. React will inject your JavaScript code into the #root div in this file.

  • src/index.js: The entry point of your React app, where the ReactDOM.render() method mounts the App component to the #root element in index.html.

  • src/App.js: The main React component that displays your app's content.

Step 6: Build for Production

When your app is ready for production, you can build it by running:

npm run build

This will create an optimized production build in the build folder. You can then deploy it to any static server like Netlify, Vercel, or GitHub Pages.

  1. Create React App with Vite

To create a React app using Vite, follow these simple steps. Vite is a modern build tool that provides a faster and leaner development experience compared to Create React App (CRA). It leverages ES modules and is optimized for speed, especially with large projects.

Step 1: Install Node.js and npm

Before you begin, make sure Node.js and npm are installed. You can check by running:

node -v
npm -v

If you don't have them installed, you can download Node.js from https://nodejs.org/.

Step 2: Create a Vite React App

To create a new React app with Vite, run the following command using npm, yarn, or pnpm. The easiest way to do this is by using the npm init command with Vite's React template.

# Using npm
npm create vite@latest my-react-app --template react

# Using yarn
yarn create vite my-react-app --template react

# Using pnpm
pnpm create vite my-react-app --template react
  • my-react-app is the name of your project directory (you can replace it with any name you prefer).

  • --template react specifies that you're using the React template provided by Vite.

Step 3: Navigate to Your Project Directory

Once the setup is complete, navigate into your project directory:

cd my-react-app

Step 4: Install Dependencies

After the Vite project is created, you need to install the dependencies using your preferred package manager:

# Using npm
npm install

# Using yarn
yarn install

# Using pnpm
pnpm install

Step 5: Start the Development Server

To start the Vite development server, run:

# Using npm
npm run dev

# Using yarn
yarn dev

# Using pnpm
pnpm dev

This will start the local development server and open your app in the browser at http://localhost:5173/. Vite uses port 5173 by default.

Step 6: Explore the Project Structure

Vite will generate a default project structure that looks like this:

my-react-app/
β”œβ”€β”€ node_modules/
β”œβ”€β”€ public/
β”‚   └── favicon.svg
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ App.css
β”‚   β”œβ”€β”€ App.jsx
β”‚   β”œβ”€β”€ index.css
β”‚   └── main.jsx
β”œβ”€β”€ .gitignore
β”œβ”€β”€ index.html
β”œβ”€β”€ package.json
β”œβ”€β”€ vite.config.js
└── README.md
  • index.html: The entry HTML file for your app. Unlike CRA, Vite directly uses this HTML file as the entry point.

  • src/main.jsx: This is the entry point of your React application. It renders the App component into the #root element in index.html.

  • src/App.jsx: The main React component where you can begin coding your app.

  • vite.config.js: This is the Vite configuration file.

Step 7: Build for Production

When your app is ready to be deployed, you can create a production build by running:

# Using npm
npm run build

# Using yarn
yarn build

# Using pnpm
pnpm build

This will output a fully optimized production build in the dist folder. You can deploy this folder to any static hosting platform like Netlify, Vercel, or GitHub Pages.

React Fragment

By default, when returning multiple elements from a React component, they need to be wrapped inside a parent element (like a div), but this can lead to unwanted markup, affecting styling and layout. React Fragment helps to solve this problem by allowing you to group elements together without adding additional nodes to the DOM.

Basic Usage

import React from 'react';

function MyComponent() {
  return (
    <React.Fragment>
      <h1>Title</h1>
      <p>This is a paragraph.</p>
    </React.Fragment>
  );
}

export default MyComponent;

This code would render as:

<h1>Title</h1>
<p>This is a paragraph.</p>

Notice there’s no parent container like a div wrapping the h1 and p elements in the final output.

Shorthand Syntax

React also provides a shorthand syntax for Fragment, which is just an empty set of tags (<> </>). This makes the code cleaner:

function MyComponent() {
  return (
    <>
      <h1>Title</h1>
      <p>This is a paragraph.</p>
    </>
  );
}

When to Use Fragments?

  1. To Avoid Extra Wrapping Elements: Fragments are useful when you don’t want to introduce unnecessary parent elements, especially when those elements may interfere with CSS styling or layout.

  2. When Mapping Arrays: Fragments are commonly used when mapping over a list of items and returning multiple children.

Example:

function ItemList({ items }) {
  return (
    <>
      {items.map(item => (
        <React.Fragment key={item.id}>
          <dt>{item.name}</dt>
          <dd>{item.description}</dd>
        </React.Fragment>
      ))}
    </>
  );
}

This prevents wrapping each dt and dd pair in an extra element like a div, which would not be semantically correct for a dl list.

Fragment Props

In some cases, you might want to apply attributes to the Fragment, like a key when rendering a list of elements. This can be done by using the long form (<React.Fragment>), but keep in mind, Fragments don’t accept props other than key.

function ItemList({ items }) {
  return (
    <>
      {items.map(item => (
        <React.Fragment key={item.id}>
          <h1>{item.name}</h1>
          <p>{item.description}</p>
        </React.Fragment>
      ))}
    </>
  );
}

In the example above, we used key to uniquely identify each React.Fragment. The shorthand (<> </>) does not support adding keys or attributes, so you’ll need to use the full <React.Fragment> syntax when doing so.

Class Component in React

A Class Component in React is one of the fundamental ways to define React components. It allows you to create components using ES6 JavaScript classes. Unlike function components, class components have access to state and lifecycle methods, making them more powerful in certain situations.

Syntax of a Class Component

A class component must:

  • Extend from React.Component (or Component if imported separately).

  • Include a render() method that returns the JSX to be displayed.

  • Optionally, maintain state and lifecycle methods.

Example

import React, { Component } from 'react';

class MyComponent extends Component {
  // State - used to store dynamic data
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  // Event handler to update state
  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  // Render method - returns JSX
  render() {
    return (
      <div>
        <h1>Count: {this.state.count}</h1>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

export default MyComponent;

Functional Components

Functional components are JavaScript functions that return React elements. They are the simplest way to define a component and are often referred to as stateless components because they couldn't manage their own state historically. However, with the introduction of React Hooks, functional components can now manage state and perform side effects.

Syntax

function MyComponent() {
  return (
    <div>
      <h1>Hello, World!</h1>
    </div>
  );
}
export default MyComponent;

Here, MyComponent is a functional component that returns JSX (JavaScript XML), which is a syntax extension of JavaScript used in React to describe what the UI should look like.

Advantages of Functional Components

  • Simpler Syntax: Functional components are more concise and easier to read.

  • Hooks: They allow the use of React Hooks like useState and useEffect, which enables functional components to handle state and side effects.

  • Performance: Functional components typically have better performance because they don’t need to deal with the this keyword, and they don’t include the extra overhead of class components.

Example with State using Hooks

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0); 
  // Declaring state using the useState Hook

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
export default Counter;

In this example, useState is a React Hook that allows us to add local state to a functional component. count is the current state, and setCount is the function to update it.

Hooks Overview

  • useState: Manages state in functional components.

  • useEffect: Handles side effects like fetching data, subscriptions, and manual DOM manipulations.

  • useContext: Allows components to access values from a React Context.

  • useReducer: Manages complex state logic, an alternative to useState.

JSX

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code inside JavaScript. It simplifies writing React components by combining markup and logic.

Key Points:

  • JSX must have one parent element.

  • You can embed JavaScript expressions in {}.

  • Attributes use camelCase (e.g., className instead of class).

Example:

function Welcome(props) {
  return <h1>Hello, {props.name}!</h1>;
}

function App() {
  return <Welcome name="Vitthal" />;
}

In this example, the Welcome component uses JSX to display "Hello, Vitthal!" by embedding the name prop inside {}.

React CSS

1. CSS in React

You can write standard CSS files and import them into your React components.

Steps:

  1. Create a regular CSS file, for example: App.css.

  2. Inside App.css, write your styles:

     .container {
       background-color: lightblue;
       padding: 20px;
       text-align: center;
     }
    
     .title {
       font-size: 24px;
       color: darkblue;
     }
    
  3. In your component (e.g., App.js), import the CSS file:

     import './App.css';
    
     function App() {
       return (
         <div className="container">
           <h1 className="title">Hello, CSS in React!</h1>
         </div>
       );
     }
    
     export default App;
    

Advantages:

  • Simple to use, especially for small projects.

  • Similar to how you'd use CSS in plain HTML.

Disadvantages:

  • All CSS is global, which can lead to conflicts if multiple components use the same class names.

2. CSS Modules in React

CSS Modules offer scoped CSS by generating unique class names to avoid conflicts. This is especially useful for large-scale React apps where global CSS can become hard to manage.

Steps:

  1. Create a CSS module file with the naming convention: [name].module.css, for example: App.module.css.

  2. Inside App.module.css, write your styles:

     .container {
       background-color: lightgreen;
       padding: 20px;
       text-align: center;
     }
    
     .title {
       font-size: 24px;
       color: darkgreen;
     }
    
  3. In your component (e.g., App.js), import the CSS module:

     import styles from './App.module.css';
    
     function App() {
       return (
         <div className={styles.container}>
           <h1 className={styles.title}>Hello, CSS Modules in React!</h1>
         </div>
       );
     }
    
     export default App;
    

How it Works:

  • The imported styles object will contain all class names as properties.

  • React automatically generates unique class names (e.g., App_container__2ftTh), preventing style conflicts between different components.

Advantages:

  • Scoped CSS: No global conflicts; styles are locally scoped to the component.

  • Encourages modular design, improving maintainability.

Disadvantages:

  • More setup steps compared to plain CSS.

  • Naming conventions like module.css must be followed.

Comparison:

FeatureRegular CSS in ReactCSS Modules
ScopeGlobal (styles can conflict)Local to the component
Ease of UseSimple to use, import, and applyRequires importing and using a styles object
CSS NamingSame class names may cause conflictsUnique, generated names prevent conflicts
Ideal forSmall projects, simple stylesLarger projects, component-based styling

GitHub Link : React Fundamentals

Β