Codementor Events

Comparing React VS HTMX: Choosing the Right Frontend Approach

Published Jun 23, 2023

Introduction:

Building modern web applications often requires combining a robust backend framework with a frontend framework to create dynamic and interactive user experiences. React and HTMX are two popular choices when it comes to frontend development. In this article, we'll explore the differences between React and HTMX, and how they can be used to create compelling web applications. We'll also provide practical examples for each approach.

React:

React has gained significant popularity in the web development community due to its component-based architecture and efficient rendering capabilities.

Using React involves setting up frontend environment powered by tools like Webpack. React components can then be used to fetch data from the backend through APIs and render it dynamically on the client-side. This approach provides a seamless user experience, as React updates only the necessary parts of the UI, avoiding full page reloads.

React Example App:

This example actively searches a contacts database as the user enters text.

We start with a search input and an empty table:

import React, { useState } from 'react';

function ContactSearch() {
  const [searchResults, setSearchResults] = useState([]);

  const handleSearch = (event) => {
    const searchTerm = event.target.value;

    fetch('/search', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ search: searchTerm }),
    })
      .then((response) => response.json())
      .then((data) => {
        setSearchResults(data);
      });
  };

  return (
    <div>
      <h3>
        Search Contacts
        <span className="htmx-indicator">
          <img src="/img/bars.svg" alt="Loading..." /> Searching...
        </span>
      </h3>
      <input
        className="form-control"
        type="search"
        name="search"
        placeholder="Begin Typing To Search Users..."
        onChange={handleSearch}
      />
      <table className="table">
        <thead>
          <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody id="search-results">
          {searchResults.map((contact) => (
            <tr key={contact.id}>
              <td>{contact.firstName}</td>
              <td>{contact.lastName}</td>
              <td>{contact.email}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default ContactSearch;

Express.js app for React frontend

const express = require('express');
const app = express();

// POST /search route
app.post('/search', (req, res) => {
  // Simulating search logic
  const searchTerm = req.body.search;
  const searchResults = [
    { id: 1, firstName: 'John', lastName: 'Doe', email: 'john@example.com' },
    { id: 2, firstName: 'Jane', lastName: 'Doe', email: 'jane@example.com' },
  ];

  // Filter the search results based on the searchTerm
  const filteredResults = searchResults.filter((result) => {
    const firstNameMatch = result.firstName.toLowerCase().includes(searchTerm.toLowerCase());
    const lastNameMatch = result.lastName.toLowerCase().includes(searchTerm.toLowerCase());
    const emailMatch = result.email.toLowerCase().includes(searchTerm.toLowerCase());

    return firstNameMatch || lastNameMatch || emailMatch;
  });

  // Simulating delay for illustration purposes
  setTimeout(() => {
    res.json(filteredResults);
  }, 1000); // Delayed response for 1 second
});

// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

HTMX:

HTMX takes a different approach by focusing on enhancing the user interface with minimal JavaScript code. HTMX allows you to add interactivity to your frontend using declarative attributes embedded directly in your HTML markup.

With HTMX we leverage the power to update individual task items without reloading the entire page. HTMX achieves this by making HTTP requests to the server in the background and updating specific elements on the page using the hx-swap attribute. This approach simplifies the development process by reducing the need for separate frontend tooling and JavaScript code.

HTMX Example App:

<h3> 
  Search Contacts 
  <span class="htmx-indicator"> 
    <img src="/img/bars.svg"/> Searching... 
   </span> 
</h3>
<input class="form-control" type="search" 
       name="search" placeholder="Begin Typing To Search Users..." 
       hx-post="/search" 
       hx-trigger="keyup changed delay:500ms, search" 
       hx-target="#search-results" 
       hx-indicator=".htmx-indicator">

<table class="table">
    <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
    </tr>
    </thead>
    <tbody id="search-results">
    </tbody>
</table>

Express.js app for HTMX frontend

const express = require('express');
const app = express();

// POST /search route
app.post('/search', (req, res) => {
  // Simulating search logic
  const searchTerm = req.body.search;
  const searchResults = [
    { id: 1, firstName: 'John', lastName: 'Doe', email: 'john@example.com' },
    { id: 2, firstName: 'Jane', lastName: 'Doe', email: 'jane@example.com' },
  ];

  // Filter the search results based on the searchTerm
  const filteredResults = searchResults.filter((result) => {
    const firstNameMatch = result.firstName.toLowerCase().includes(searchTerm.toLowerCase());
    const lastNameMatch = result.lastName.toLowerCase().includes(searchTerm.toLowerCase());
    const emailMatch = result.email.toLowerCase().includes(searchTerm.toLowerCase());

    return firstNameMatch || lastNameMatch || emailMatch;
  });

  // Generate the HTML for search results
  const html = filteredResults
    .map((result) => `<tr><td>${result.firstName}</td><td>${result.lastName}</td><td>${result.email}</td></tr>`)
    .join('');

  // Simulating delay for illustration purposes
  setTimeout(() => {
    res.send(html);
  }, 1000); // Delayed response for 1 second
});

// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

Choosing the Right Approach:

When deciding between React and HTMX, consider the following factors:

  1. Project Complexity: If your application requires complex UI interactions, real-time updates, and a rich set of reusable components, React might be the better choice. React's component-based architecture and vast ecosystem provide the necessary tools to handle such scenarios.

  2. Development Speed: HTMX can be an excellent choice for projects where simplicity and speed of development are paramount. With HTMX, you can add interactivity to your frontend directly, reducing the need for extensive JavaScript development and tooling setup.

  3. Team Expertise: Consider the skills and expertise of your development team. If they are well-versed in React and comfortable with the React ecosystem, React may be the preferred option. On the other hand, if your team prefers a simpler frontend approach, HTMX could be a better fit.

Conclusion:

Both React and HTMX offer powerful frontend solutions. React provides a comprehensive framework for building complex, interactive web applications, while HTMX simplifies interactivity by embedding declarative attributes directly in HTML markup. Choosing between the two depends on your project requirements, complexity, and the expertise of your development team. Evaluate the trade-offs, consider your specific needs, and select the approach that aligns best with your goals.

Discover and read more posts from Victor H
get started
post commentsBe the first to share your opinion
Erin Lowry
5 months ago

React’s component-based architecture enables programmers to design reusable user interface components. Maintainability and modularity are encouraged by this. React effectively updates and renders changes to the user interface via the use of a virtual DOM. Improved performance may result from this, particularly in sophisticated applications.

With HTMX’s (geometry dash meltdown) emphasis on progressive enhancement, developers may include dynamic behavior into pre-existing HTML with a minimum amount of JavaScript. It is intended to improve apps that are now delivered by servers. HTMX defines dynamic behavior by using declarative HTML properties. For developers who would rather work with HTML instead of a separate JavaScript framework, this may make it more accessible.

Shagufta shamid
10 months ago

SyncfusionDropdownMultiselect is a component provided by Syncfusion, a software development company that offers a wide range of UI controls and libraries. Unfortunately, without specific details about the error you’re encountering, it’s challenging to provide a precise solution. However, here are some general steps you can take to troubleshoot the issue here https://www.techspotty.com/:

Check for console errors: Open the browser developer tools (usually by pressing F12) and check the console for any error messages. Errors reported in the console can provide valuable insights into the cause of the issue.

george
10 months ago

This informative article compares React and HTMX, two popular frameworks for modern web development. It explains that React is favored for its component-based architecture and efficient rendering, while HTMX focuses on adding interactivity with minimal JavaScript. React updates specific UI parts without reloading the entire page, while HTMX achieves this through background HTTP requests and the hx-swap attribute. The article provides practical examples for each approach, enabling readers to make informed choices based on their project needs. https://bestpickleballreviews.com

Show more replies