• Lalit Barad
  • Posts
  • Mastering Reactjs Fundamentals: Practical Code Examples

Mastering Reactjs Fundamentals: Practical Code Examples

Mastering Reactjs Fundamentals: Practical Code Examples

In today's digital age, having a strong grasp of Reactjs is essential for any aspiring web developer. Reactjs, often simply referred to as React, is a popular JavaScript library for building user interfaces. It was developed by Facebook and has gained widespread adoption in the industry due to its efficiency and flexibility.

What is Reactjs?

At its core, Reactjs is a declarative, efficient, and flexible JavaScript library for building user interfaces. It allows developers to create interactive UIs with ease, by breaking down the entire interface into reusable components. This component-based architecture makes it easy to manage and maintain complex UIs, enabling developers to write cleaner and more organized code.

Why Choose Reactjs for Your Project?

There are several reasons why Reactjs stands out as a preferred choice for web development projects. One of the key advantages of Reactjs is its virtual DOM implementation, which allows for faster rendering of UI components. Additionally, Reactjs promotes code reusability and modular development, making it easier to maintain and scale projects over time. With a thriving community and extensive documentation, Reactjs is a solid choice for projects of all sizes.

Reactjs Fundamentals

In the world of web development, Reactjs has become a popular choice for building interactive user interfaces. Understanding the fundamentals of Reactjs is essential for anyone looking to dive into this powerful library. Let's explore some key concepts that form the foundation of Reactjs.

JSX - The Syntax Extension

JSX, or JavaScript XML, is an extension to JavaScript that allows us to write HTML-like code within our JavaScript files. This makes it easier to work with React components as we can define our UI elements in a more declarative manner. JSX may seem like a new concept at first, but once you get used to it, you'll find it to be a powerful tool for creating dynamic UIs.

JSX allows you to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods.

import React from 'react';

// Define a component using JSX
function HelloWorld() {
  // JSX syntax that looks like HTML
  return <div>Hello, World!</div>;
}

export default HelloWorld;

Components and Props

At the core of Reactjs are components - reusable pieces of UI that can be composed together to build complex interfaces. Components can be either class-based or functional, depending on your preference. Props are used to pass data from a parent component to a child component. By mastering the concept of components and props, you'll be well on your way to creating scalable and maintainable React applications.

Components let you split the UI into independent, reusable pieces. Props are how you pass data from parent to child components.

import React from 'react';

// Functional component with props
function Greeting(props) {
  // Access props passed from the parent component
  return <h1>Hello, {props.name}!</h1>;
}

export default Greeting;

Understanding State and Lifecycle

State is a crucial concept in Reactjs that allows components to manage their own data. When a component's state changes, React automatically re-renders the component, updating the UI to reflect the new state. Lifecycle methods, such as componentDidMount and componentWillUnmount, help us manage the behavior of our components at different stages of their lifecycle.

State allows React components to change their output over time in response to user actions, network responses, etc. Lifecycle methods let you hook into specific moments in a component's life.

import React, { Component } from 'react';

class Counter extends Component {
  // Initializing state
  state = { count: 0 };

  componentDidMount() {
    // Called after the component is mounted
    this.timer = setInterval(() => this.setState({ count: this.state.count + 1 }), 1000);
  }

  componentWillUnmount() {
    // Cleanup before the component is removed
    clearInterval(this.timer);
  }

  render() {
    // Render based on the current state
    return <div>Count: {this.state.count}</div>;
  }
}

export default Counter;

Handling Events

Interactivity is key in modern web applications, and React makes it easy to handle user events such as clicks, keystrokes, and form submissions. By using event handlers like onClick and onChange, you can define how your components respond to user input. Understanding how to handle events in React will make your applications more engaging and user-friendly.

React elements offer event handling similar to handling events on DOM elements. However, React events are named using camelCase, rather than lowercase.

import React, { useState } from 'react';

function ButtonClick() {
  const [count, setCount] = useState(0);

  // Function to handle click event
  function handleClick() {
    setCount(count + 1);
  }

  return (
    <button onClick={handleClick}>
      Click Me! Count: {count}
    </button>
  );
}

export default ButtonClick;

Conditional Rendering

In many cases, you'll need to conditionally render different UI elements based on certain criteria. React provides a simple and intuitive way to achieve this by using conditional statements within your components. Whether you need to show or hide specific content, conditional rendering in React allows you to create dynamic and adaptive interfaces.

import React from 'react';

function WelcomeUser(props) {
  // Conditional rendering based on isLoggedIn prop
  if (props.isLoggedIn) {
    return <h1>Welcome back!</h1>;
  } else {
    return <h1>Please sign up.</h1>;
  }
}

export default WelcomeUser;

Lists and Keys

Working with lists of data is a common task in web development, and React makes it easy to render dynamic lists using the map function. Keys are a special attribute that helps React identify each list item and efficiently update the DOM when changes occur. By understanding how to work with lists and keys in React, you can create dynamic and performant UIs.

import React from 'react';

function NumberList(props) {
  const numbers = props.numbers;
  // Map through numbers array to create a list of elements
  const listItems = numbers.map((number) =>
    // Assign a unique "key" prop to each list item
    <li key={number.toString()}>{number}</li>
  );
  return <ul>{listItems}</ul>;
}

export default NumberList;

Forms and Controlled Components

Forms are an essential part of many web applications, and React simplifies form management using controlled components. By maintaining the form data within React's state and updating it through event handlers, you can create interactive and responsive forms that accurately reflect user input.

import React, { useState } from 'react';

function NameForm() {
  const [name, setName] = useState('');

  function handleSubmit(event) {
    alert('A name was submitted: ' + name);
    event.preventDefault();
  }

  function handleChange(event) {
    setName(event.target.value);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={handleChange} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

export default NameForm;

Lifting State Up

Sometimes, you'll find the need to share state between multiple components that don't have a direct parent-child relationship. In such cases, lifting state up is a common pattern in React where you move the shared state to the closest common ancestor of the components. This allows for better data flow and easier management of state across your application.

import React, { useState } from 'react';

function TemperatureInput(props) {
  function handleChange(e) {
    props.onTemperatureChange(e.target.value);
  }

  return (
    <div>
      <input value={props.temperature} onChange={handleChange} />
    </div>
  );
}

function Calculator() {
  const [temperature, setTemperature] = useState('');

  function handleTemperatureChange(temperature) {
    setTemperature(temperature);
  }

  return (
    <div>
      <TemperatureInput temperature={temperature} onTemperatureChange={handleTemperatureChange} />
    </div>
  );
}

export default Calculator;

Composition vs Inheritance

React encourages the use of composition over inheritance when building component hierarchies. By composing smaller components together to create more complex ones, you can achieve better code reusability and maintainability. This approach fosters a more flexible and modular design, making it easier to update and extend your components as your application grows.

import React from 'react';

function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}
    </div>
  );
}

function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        Welcome
      </h1>
      <p className="Dialog-message">
        Thank you for visiting our spacecraft!
      </p>
    </FancyBorder>
  );
}

export default WelcomeDialog;

Thinking in React

One of the many great parts of React is the way it makes you think about apps as you build them. Let's build a simple searchable product table using React.

  1. Break The UI Into A Component Hierarchy: The first thing you'll want to do is to draw boxes around every component (and subcomponent) in the mock and give them all names.

  2. Build A Static Version in React: The easiest way is to build a version that takes your data model and renders the UI but has no interactivity.

  3. Identify The Minimal (but complete) Representation Of UI State: To make your UI interactive, you need to be able to trigger changes to your underlying data model. React makes this easy with state.

  4. Identify Where Your State Should Live: Identify which component mutates, or owns, this state.

  5. Add Inverse Data Flow: This makes your component truly reusable and encapsulated. It doesn't know whether it's being used in a filter or for a form input.

import React, { useState } from 'react';

function SearchBar({ filterText, inStockOnly, onFilterTextChange, onInStockChange }) {
  return (
    <form>
      <input
        type="text"
        placeholder="Search..."
        value={filterText}
        onChange={(e) => onFilterTextChange(e.target.value)}
      />
      <p>
        <input
          type="checkbox"
          checked={inStockOnly}
          onChange={(e) => onInStockChange(e.target.checked)}
        />{' '}
        Only show products in stock
      </p>
    </form>
  );
}

function ProductTable({ products, filterText, inStockOnly }) {
  const rows = products
    .filter((product) => product.name.includes(filterText) && (!inStockOnly || product.stocked))
    .map((product) => (
      <tr key={product.name}>
        <td>{product.name}</td>
        <td>{product.price}</td>
      </tr>
    ));

  return (
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>{rows}</tbody>
    </table>
  );
}

function FilterableProductTable({ products }) {
  const [filterText, setFilterText] = useState('');
  const [inStockOnly, setInStockOnly] = useState(false);

  return (
    <div>
      <SearchBar
        filterText={filterText}
        inStockOnly={inStockOnly}
        onFilterTextChange={setFilterText}
        onInStockChange={setInStockOnly}
      />
      <ProductTable products={products} filterText={filterText} inStockOnly={inStockOnly} />
    </div>
  );
}

const PRODUCTS = [
  { category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football' },
  { category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball' },
  { category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball' },
  { category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch' },
  { category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5' },
  { category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7' }
];

function App() {
  return <FilterableProductTable products={PRODUCTS} />;
}

export default App;

This example covers several important concepts in React:

  • Component Hierarchy: The app is divided into components that represent parts of the UI.

  • Props: Data is passed from parent to child components through props.

  • State: The state is used to keep track of user input and filters.

  • Lifting State Up: The state is lifted up to the common ancestor (FilterableProductTable) to be shared between siblings (SearchBar and ProductTable).

  • Controlled Components: Form elements like <input> are controlled by React, making the UI the single source of truth.

By following the "Thinking in React" methodology, you start with a mock and end up with a fully functional app. This approach to React development helps in designing more scalable and maintainable applications.

Creating a Simple React Component

To start, let's create a basic React component called HelloWorld. This component will simply render a greeting message on the screen. Here's the code snippet:

 import React from 'react';

class HelloWorld extends React.Component { render() { return

Hello, World!

; } }

 export default HelloWorld; ```

Implementing State and Lifecycle Methods

Next, let's explore how to incorporate state and lifecycle methods in a React component. We will create a counter component that increments a value every second. Here's the code snippet:

 import React from 'react';

class Counter extends React.Component { state = { count: 0 };

componentDidMount() { this.interval = setInterval(() => { this.setState({ count: this.state.count + 1 }); }, 1000); }

componentWillUnmount() { clearInterval(this.interval); }

render() { return

Count: {this.state.count}

; } }
export default Counter; 
 

Building a Todo List Application

Let's build a simple Todo List application with React. This application will include functionality to add tasks, remove them, and mark them as completed. We'll employ components, state, and event handling to make our Todo List interactive.

Step 1: Setting Up the Project

Ensure you have Node.js installed on your machine and then create a new React app:

npx create-react-app todo-list-app
cd todo-list-app
npm start

Step 2: Creating the Todo List Application

Replace the content of src/App.js with the following code snippet:

import React, { useState } from 'react';
import './App.css';

function App() {
  const [task, setTask] = useState('');
  const [todos, setTodos] = useState([]);

  const addTask = () => {
    if (!task) return; // Don't add empty tasks
    setTodos([...todos, { text: task, completed: false }]);
    setTask('');
  };

  const toggleTask = (index) => {
    const newTodos = [...todos];
    newTodos[index].completed = !newTodos[index].completed;
    setTodos(newTodos);
  };

  const deleteTask = (index) => {
    const newTodos = [...todos].filter((_, i) => i !== index);
    setTodos(newTodos);
  };

  return (
    <div className="app">
      <input
        type="text"
        value={task}
        onChange={(e) => setTask(e.target.value)}
        placeholder="Add a new task"
      />
      <button onClick={addTask}>Add</button>
      <ul>
        {todos.map((todo, index) => (
          <li key={index} style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>
            {todo.text}
            <button onClick={() => toggleTask(index)}>Toggle</button>
            <button onClick={() => deleteTask(index)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;


Let's build a simple Todo List application with React. This application will include functionality to add tasks, remove them, and mark them as completed. We'll employ components, state, and event handling to make our Todo List interactive.

Step 1: Setting Up the Project

Ensure you have Node.js installed on your machine and then create a new React app:

bashCopy code

npx create-react-app todo-list-app cd todo-list-app npm start

Step 2: Creating the Todo List Application

Replace the content of src/App.js with the following code snippet:

jsxCopy code

import React, { useState } from 'react'; import './App.css'; function App() { const [task, setTask] = useState(''); const [todos, setTodos] = useState([]); const addTask = () => { if (!task) return; // Don't add empty tasks setTodos([...todos, { text: task, completed: false }]); setTask(''); }; const toggleTask = (index) => { const newTodos = [...todos]; newTodos[index].completed = !newTodos[index].completed; setTodos(newTodos); }; const deleteTask = (index) => { const newTodos = [...todos].filter((_, i) => i !== index); setTodos(newTodos); }; return ( <div className="app"> <input type="text" value={task} onChange={(e) => setTask(e.target.value)} placeholder="Add a new task" /> <button onClick={addTask}>Add</button> <ul> {todos.map((todo, index) => ( <li key={index} style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}> {todo.text} <button onClick={() => toggleTask(index)}>Toggle</button> <button onClick={() => deleteTask(index)}>Delete</button> </li> ))} </ul> </div> ); } export default App;

Explanation:

  • State Management: We use useState to manage the tasks (todos) and the current input value (task). The todos state is an array of todo objects, each containing a text and a completed property.

  • Adding Tasks: The addTask function updates the todos state with a new task, resetting the task state to clear the input field.

  • Toggling Tasks: The toggleTask function changes the completion status of a task. It finds the task by its index, modifies its completed status, and then updates the todos state with the new array.

  • Deleting Tasks: The deleteTask function removes a task from the todos array based on its index.

  • Rendering: The app renders an input field for adding new tasks, a button to submit the task, and a list of tasks. Each task in the list is rendered with "Toggle" and "Delete" buttons to control its status and presence.

Step 3: Adding Styles (Optional)

Create a src/App.css file or modify the existing one to style your application. Here's a simple example:

.app {
  max-width: 600px;
  margin: 30px auto;
  padding: 20px;
  text-align: center;
}

input[type="text"] {
  margin-right: 10px;
  padding: 10px;
  width: 70%;
}

button {
  padding: 10px;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  margin-top: 10px;
  text-align: left;
}

This basic Todo List application demonstrates key React concepts such as component structure, state management, and event handling. You can expand on this foundation by adding features like editing tasks, saving the list to local storage, or even integrating an API.React

Reply

or to participate.