DEV Community

Cover image for Learn React The Lazy Way in 2023
Scofield Idehen
Scofield Idehen

Posted on • Edited on • Originally published at blog.learnhub.africa

Learn React The Lazy Way in 2023

React is a powerful JavaScript library used for building user interfaces. It allows developers to create interactive and dynamic web applications with ease.

In this article, we will explore what React is, why it's worth learning in 2023, and the benefits of adopting a gradual learning approach.

We'll also cover setting up the development environment, building components, managing state, handling events and user input, working with lists, conditional rendering, and styling React components.

 Introduction to React

  • What is React?

React is a JavaScript library developed by Facebook. It provides a declarative and efficient way to build user interfaces by breaking them into reusable components. React follows a component-based architecture, allowing developers to create encapsulated and self-contained UI elements that can be composed to form complex applications.

  • Why learn React in 2023?
  1. Growing demand: The demand for React developers continues to rise in the industry. Many companies and organizations are adopting React for their projects, making it a valuable skill in your arsenal.
  1. Popularity and community support: React has gained immense popularity due to its performance, scalability, and strong community support. Learning React means tapping into a vast ecosystem of resources, tutorials, and libraries.
  1. Advantages of using React: React offers numerous benefits, such as virtual DOM rendering for optimal performance, a rich set of UI components, and seamless integration with other libraries or frameworks. These advantages make React a compelling choice for web development.
  • Benefits of learning React the lazy way.

Learning React incrementally and at your own pace can be an efficient approach for newcomers. By taking a gradual learning path, you can:

  1. Avoid feeling overwhelmed: React can be initially intimidating, but by learning incrementally, you can grasp its concepts without feeling overwhelmed.
  1. Understand key concepts: A gradual learning approach allows you to focus on understanding key concepts, such as components, props, state, and hooks, before diving into advanced topics.
  1. Hands-on examples: Practical examples and hands-on exercises help solidify your understanding of React's core concepts and enable you to apply them in real-world scenarios.

Setting Up Your Development Environment

  • Installing Node.js and npm

To develop with React, you must install Node.js and npm (Node Package Manager) on your machine. Follow these steps:

  1. Visit the Node.js website and download the latest LTS version for your operating system.
  2. Run the installer and follow the on-screen instructions.
  3. After installation, open your terminal or command prompt and type node -v and npm -v to verify that Node.js and npm are installed correctly.
  • Setting up a new React project using Create React App

Create React App is a popular tool that helps you set up a new React project with a predefined folder structure and development environment configuration. Here's how to use it:

  1. Open your terminal or command prompt and run the following command: npx create-react-app my-react-app. Replace "my-react-app" with the desired name of your project.
  2. Once the command completes, navigate into the project directory: cd my-react-app.
  3. Start the development server by running: npm start. This will launch your React application in the browser.
  • Familiarizing with the project structure

Understanding the structure of a React project is essential for efficient development. The key files and directories you'll encounter in a typical React project are:

  1. src: This directory contains the main source code files of your React application.
  2. public: The public directory contains the HTML file that serves as the entry point for your application.
  3. src/index.js: This file is the entry point for your React application. It renders the root component and mounts it into the DOM.
  4. src/App.js: This file contains the main component of your application. It serves as the starting point for building your UI.
  5. src/components: The components directory is where you can store your reusable components. It helps in organizing your code and promotes reusability.
  6. src/styles: This directory stores CSS or styling-related files for your components.

Building Components

  • Understanding React components

Components are the building blocks of a React application. They are reusable, self-contained, and encapsulate specific UI functionality. There are two types of components in React:

  • Functional components: These are JavaScript functions that receive props as input and return JSX (a syntax extension for JavaScript that resembles HTML) to define the component's structure and content.
  • Class components: These are ES6 classes that extend the React.Component class. They have more features and capabilities, including state management and lifecycle methods.
  • Creating functional components

Functional components are simpler and recommended for most use cases. Here's an example of a basic functional component:

import React from 'react';

const MyComponent = (props) => {
  return <div>{props.message}</div>;
};

export default MyComponent;

In this example, we define a functional component called MyComponent that receives a message prop and renders it inside a <div> element.

  • Using class components

Class components are useful when you need to manage state or use lifecycle methods. Here's an example of a class component:


import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}

export default MyComponent;

In this example, we define a class component called MyComponent with an initial state count and a button that increments the count when clicked.

  • Exploring React hooks for state and lifecycle management

React hooks are functions introduced in React 16.8 that allow functional components to use state and lifecycle methods. They provide a simpler and more concise way to manage component logic. Here's an example of using hooks:

import React, { useState, useEffect } from 'react';

const MyComponent = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default MyComponent

In this example, we use the useState hook to declare the state variable count and the setCount function to update it. The useEffect hook is used to perform side effects, such as updating the document title, when the count changes.

Managing State in React

  • Introduction to React state

State represents the data that can change over time in a React component. It enables components to be dynamic and responsive to user interactions. State allows you to store and update values that affect the component's rendering and behavior.

  • Working with state in functional components

In functional components, state can be managed using the useState hook. Here's an example:


import React, { useState } from 'react';

const MyComponent = () => {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
};

export default MyComponent;

In this example, we declare a state variable count using the useState hook. The setCount function is used to update the value of count. When the button is clicked, the increment function is called, which updates the state by incrementing the count value.

  • State management in class components

In class components, state is managed using the this.state object and the this.setState() method. Here's an example:


import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  increment() {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.increment()}>Increment</button>
      </div>
    );
  }
}

export default MyComponent;

In this example, we initialize the state in the constructor using this.state. The increment method is used to update the state by calling this.setState() with the new state value. When the button is clicked, the increment method is invoked.

  • Implementing lifecycle methods for state management

In class components, lifecycle methods can be used for additional control over state management. For example, the componentDidMount method is called when the component is first mounted to the DOM. Here's an example:


import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  componentDidMount() {
    console.log('Component is mounted!');
  }

  increment() {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.increment()}>Increment</button>
      </div>
    );
  }
}

export default MyComponent;

In this example, the componentDidMount method is used to log a message when the component is mounted. You can use other lifecycle methods like componentDidUpdate or componentWillUnmount to handle state changes at different stages of the component's lifecycle.

Handling Events and User Input

  • Adding event handlers to components

Event handlers allow components to respond to user interactions such as clicks, key presses, or form submissions.

In class components, event handlers are typically bound using the this keyword and class methods. Here's an example of a click event handler in a class component:

import React from 'react';

class MyComponent extends React.Component {
  handleClick() {
    console.log('Button clicked!');
  }

  render() {
    return <button onClick={this.handleClick}>Click me</button>;
  }
}

export default MyComponent;

In this example, the handleClick method logs a message when clicking the button. The method is passed as a reference to the onClick event handler.

Capturing and handling user input can be achieved by utilizing controlled components. Controlled components allow React to manage the state of form elements, enabling you to effectively capture and handle user input.

Here's an example of creating a controlled input element using state:


import React, { useState } from 'react';

const MyForm = () => {
  const [inputValue, setInputValue] = useState('');

  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    // Handle form submission with inputValue
    console.log('Submitted value:', inputValue);
    setInputValue('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder="Enter a value"
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;

In this example, the inputValue state variable is used to store the value of the input element. The handleChange function is triggered when the input value changes, updating the state accordingly. The form's onSubmit event handler is called when the form is submitted, where you can handle the form data, reset the input value, or perform other actions.

  • Using controlled components with form validation

Controlled components enable you to implement form validation and handle form submissions based on the input values. Here's an example:

import React, { useState } from 'react';

const MyForm = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');

  const handleNameChange = (event) => {
    setName(event.target.value);
  };

  const handleEmailChange = (event) => {
    setEmail(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();

    if (!name || !email) {
      setError('Please fill in all fields.');
      return;
    }

    // Handle form submission with name and email
    console.log('Submitted name:', name);
    console.log('Submitted email:', email);

    setName('');
    setEmail('');
    setError('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={name}
        onChange={handleNameChange}
        placeholder="Enter your name"
      />
      <input
        type="email"
        value={email}
        onChange={handleEmailChange}
        placeholder="Enter your email"
      />
      <button type="submit">Submit</button>
      {error && <p>{error}</p>}
    </form>
  );
};

export default MyForm;

In this example, the form includes name and email input fields. The handleSubmit function validates the inputs and displays an error message if any field is empty. If the form passes validation, it can handle the submitted data accordingly.

  • Installing React Developer Tools extension

React Developer Tools is a browser extension that provides helpful tools for debugging and inspecting React components. Here's how to install it:

  1. Open your web browser and search for the "React Developer Tools" extension.

Choose the appropriate extension for your browser (e.g., Chrome, Firefox) and click on the download/install button.

  1. Once installed, you can find the React Developer Tools icon in your browser's toolbar.

React Developer Tools allows you to inspect component hierarchies, view component props and state, and track component updates, among other useful features. It greatly assists in debugging and understanding your React applications.

Working with Lists and Conditional Rendering

  • Rendering lists of data in React

When working with dynamic data in React, it is essential to be able to render lists of items dynamically. This allows us to avoid manually writing markup for each item and instead utilize React's ability to iterate over arrays and render list items efficiently.

To render a list in React, we can iterate over an array using JavaScript's map function and dynamically generate the corresponding list elements. This approach simplifies the process and allows for a more flexible and scalable solution.

  • Using the map function to iterate over arrays

The map function in JavaScript allows us to transform each element of an array and return a new array. In React, we can utilize the map function to iterate over arrays and generate dynamic list elements.

By mapping over an array of data, we can dynamically render list items by returning JSX elements for each item. It's important to assign a unique key prop to each rendered element to help React update and reconcile the list efficiently.

const names = ["Alice", "Bob", "Charlie"];

const NameList = () => {
  return (
    <ul>
      {names.map((name, index) => (
        <li key={index}>{name}</li>
      ))}
    </ul>
  );
};

In the above example, we iterate over the names array using the map function and return a <li> element for each name. The key prop is assigned with the index parameter to ensure a unique identifier for each list item.

  • Conditional rendering based on state or props

Conditional rendering involves displaying different components or content based on certain conditions. React provides several approaches for implementing conditional rendering, allowing us to control what gets rendered based on the component's state or props.

We can conditionally render components using logical expressions within JSX. By evaluating a condition, we can choose which component or content to render dynamically.

Example: Conditionally rendering a component based on a flag

const Greeting = ({ isLoggedIn }) => {
  return (
    <div>
      {isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>}
    </div>
  );
};

In the above example, the Greeting component receives a prop called isLoggedIn. Depending on the value of isLoggedIn, the component conditionally renders either a "Welcome back!" message or a "Please log in." message.

Styling React Components

 Inline styles and style objects

React allows applying inline styles directly to components using JavaScript objects. Inline styles offer flexibility and allow for dynamic computation of styles based on component props or state.

Inline styles are specified as objects; each CSS property is written in camelCase format. However, it's important to note the pros and cons of using inline styles before extensively relying on them.

Pros of Inline Styles

  • Directly apply styles without external CSS files
  • Enable dynamic computation of styles based on component props or state

Cons of Inline Styles

  • Increased verbosity and harder to read compared to traditional CSS
  • Lack of separation between styles and component logic, which can make maintenance challenging
  • CSS modules for component-specific styles

CSS modules provide a way to write component-specific styles without the concern of global CSS class name collisions.

We can encapsulate styles within individual components using CSS modules, making it easier to maintain and reuse styles across the application.

To use CSS modules, we create a separate CSS file for each component and import it into the corresponding React component file. The styles defined in the CSS file become locally scoped to the component, ensuring they do not interfere with other components.

Example: Using CSS modules in a React component

import styles from './Button.module.css';
const Button = () => {
  return <button className={styles.button}>Click me!</button>;
};

In the above example, we import the CSS module Button.module.css and assign it to the styles object. We then apply the button class from the styles object to the className prop of the <button> element. This ensures that the styles defined in the CSS module are applied specifically to the Button component.

  • Using CSS frameworks with React

CSS frameworks, such as Bootstrap and Material-UI, provide pre-designed components and styling conventions that can accelerate development.

Integrating CSS frameworks with React allows us to leverage their rich set of styles and components while building our applications.

To use a CSS framework with React, we typically include the necessary CSS or JavaScript files provided by the framework in our project. We can then utilize the framework's components and styles within our React components.

It's important to refer to the documentation of the specific CSS framework for detailed instructions on integrating it with React and using its features.

Overview of popular CSS frameworks (e.g., Bootstrap, Tailwind CSS)

Bootstrap is a widely adopted CSS framework that provides a comprehensive set of pre-designed styles and components.

It offers a responsive grid system, ready-made UI components, and a robust collection of CSS classes. Bootstrap is known for its simplicity and versatility, making it suitable for various projects. It also provides extensive documentation and customization options.

Tailwind CSS is another popular CSS framework that takes a different approach. Instead of pre-designed components, Tailwind CSS offers a utility-first approach.

It provides a large set of small utility classes you can combine to build custom styles. This approach gives you more control and flexibility over your designs, allowing easy customization.

Integrating CSS frameworks with React projects is relatively straightforward. Bootstrap and Tailwind CSS offer dedicated packages that can be installed using package managers like npm or yarn.

Once you have installed the framework, you can import the necessary CSS files or components into your React components.

To apply pre-defined styles and components from CSS frameworks, you can start by exploring the documentation provided by the framework.

Here are some basic examples to help you.

To get started with Bootstrap in your React project, follow these steps:

Install Bootstrap package

You can install Bootstrap using a package manager like npm or yarn. Open your terminal and run the following command:

npm install bootstrap

Import Bootstrap CSS

In your React component, import the Bootstrap CSS file to apply the predefined styles. You can do this by adding the following line at the top of your component file:

import 'bootstrap/dist/css/bootstrap.css';

Use Bootstrap components and classes.

Once you've imported the Bootstrap CSS, you can start using its components and classes in your JSX code. Here are a few examples:

Using a Bootstrap Button

import React from 'react';

const MyComponent = () => {
  return (
    <button className="btn btn-primary">Click me</button>
  );
}

export default MyComponent;

Creating a Bootstrap Card

import React from 'react';

const MyComponent = () => {
  return (
    <div className="card">
      <img src="image.jpg" className="card-img-top" alt="Card Image" />
      <div className="card-body">
        <h5 className="card-title">Card Title</h5>
        <p className="card-text">Some quick example text to build on the card.</p>
        <a href="#" className="btn btn-primary">Read More</a>
      </div>
    </div>
  );
}

export default MyComponent;

These examples demonstrate using Bootstrap's predefined styles and components in your React components.

Refer to the Bootstrap documentation for more examples and details on available components and classes. Bootstrap offers many options for buttons, forms, typography, layout, etc.

Follow the series by joining our subscription list to second the second part of this article.

If you find this post exciting, find more exciting posts like this on Learnhub Blog; we write everything tech from Cloud computing to Frontend Dev, Cybersecurity, AI and Blockchain.

Top comments (4)

Collapse
 
artydev profile image
artydev

Thank you Scofield
Here is modified version of our code in PLainJS
DevToForm

Collapse
 
scofieldidehen profile image
Scofield Idehen

I will look into it.

Thanks.

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

Collapse
 
scofieldidehen profile image
Scofield Idehen

Thanks. This is so cool