Simply copy and paste the following command line in your terminal to create your first Strapi project.
npx create-strapi-app
my-project
When building web applications, JavaScript libraries such as React.js comes to mind. This UI library has revolutionized web application development and improved interactivity between applications and users.
While React has made significant strides in enhancing web interactivity, it also comes with a certain level of complexity. This is where HTMX, steps in. It aims to address this complexity by providing a simpler approach to achieving interactivity on the web.
In this article, we'll examine HTMX, compare it to React to see how it ranks and build a Task Manager using HTMX!
HTMX stands for Hypertext markup extension. It was created by Carson Gross to enhance server-rendered HTML pages. HTMX is a lightweight Javascript that lets you build dynamic web applications using plain HTML with minimal Javascript code.
It extends HTML's capabilities by introducing custom attributes. What do these attributes do? They send behind-the-scenes requests in the form of AJAX from the frontend to the backend and render the returned response content on the screen.
The idea with HTMX is that, unlike React, Vue, or Angular, you're not exchanging data between the frontend and backend. Still, instead, your backend prepares the HTML that should be rendered on the screen, which could be an entire page or a fragment.
The driving force behind HTMX is the extension of HTML with custom attributes that enable AJAX requests and content manipulations. Some of the custom attributes include:
hx-get
: performs a GET to the supplied URL.hx-post
: sends a POST to the supplied URL.hx-select
: choose content to substitute from a response.hx-swap
: determines how the material is swapped in outerHTML, beforeend, afterend, etc.hx-target
: specifies the target element to be swapped.hx-trigger
: provides the event that prompts the request.hx-delete
: performs a DELETE on the supplied URL.hx-put
: Sends a PUT to the supplied URL.Let’s take a look at an example below:
1
2
<button hx-post="/like" hx-target="likes">Like</button>
<span id="likes">0</span>
In the code above, we are telling the browser that when a user clicks the like button
, send an AJAX POST request to the /like
endpoint and then place the response inside the <span>
element with the id
called like
, as this will update the number of likes dynamically.
Now that we have a clear understanding of how HTMX works, let’s go ahead and compare it to React.
In terms of a learning curve, HTMX stands out as it is more approachable for developers familiar with HTML.
React, in contrast, presents a more challenging learning curve due to its heavy reliance on JSX and other JavaScript concepts.
Regarding simplicity, efficient interactions, and backend-driven applications, Htmx is mainly suited for building as it only requires dynamic content loading, form submissions without page reloads, and fundamental client-side interactions.
React, on the other hand, is a go-to choice for building complex, single-page applications (SPAs) that offer a rich user experience.
HTMX leans towards a more declarative deployment style, which utilizes HTML attributes to specify the behavior of elements without having to write a significant amount of JavaScript code.
In contrast, React employs a more immparative programming style.
HTMX forms work by enhancing the regular HTML forms with custom features to manage dynamic behaviors like AJAX submissions.
Below is an example that submits HTML forms using AJAX and updates a part of the page with the response:
1
2
3
4
5
6
7
8
9
<form hx-post="/submit" hx-target="#result">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required />
<button type="submit">Submit</button>
</form>
<div id="result"></div>
<script src="https://unpkg.com/htmx.org@1.8.0"></script>
In the code above, the hx-post="/submit"
specifies that the form should be submitted using a POST request to /submit
. The hx-target="#result"
then specifies the element that will be updated with the server response.
React forms require additional setup since they are often controlled within a component, which uses state management to handle input values and form submissions. This gives you more control over the form's behavior and enables for complicated validation and dynamic updates.
Below is an example of a basic React.js form component that handles state and form submission:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React, { useState } from 'react';
function MyForm() {
const [name, setName] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
// Handle form submission logic here
console.log('Form submitted with name:', name);
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
<button type="submit">Submit</button>
</form>
);
}
export default MyForm;
In the code above, the input field is controlled by the component's state, ensuring any changes are reflected in the state.
HTMX components are created by combining normal HTML elements with interactive properties. HTMX components enhance certain elements or areas of a page, making them dynamic and responsive without the need for a comprehensive component architecture.
React components are self-contained and reusable user interface elements. They can be used together to develop complex UI hierarchies.
When deciding between HTMX and React, several essential considerations must be considered, including the project's objectives as well as the capabilities of the development team.
These factors are critical in identifying the most appropriate framework for your project. Below are some of them:
If you're looking to emphasize simplicity, efficiency, and rapid development, HTMX is the preferred choice for your project. It is useful especially in backend driven-application scenarios where the frontend largely displays data retrieved from the server.
If you're looking for an application that requires advanced interaction, scalability, and a rich user experience, React should be your go-to choice.
While HTMX offers you a simple and straightforward approach to building web applications, there are other HTMX alternatives that can also help do the job. Some of these are:
HTMX is a simple as simple as loading it via CDN into your webpage:
1
<script src="https://unpkg.com/htmx.org@1.9.12" integrity="sha384-ujb1lZYygJmzgSwoxRggbCHcjc0rB2XoQrxeTUQyRjrOnlCoYta87iKBWq3EsdM2" crossorigin="anonymous"></script>
While this is regarded as the fastest way to use HTMX, it is not advisable using it for production
You could also self-serve through a minified library or install it via npm:
npm install htmx.org
NOTE: If you encounter permission access error, please run the installation as an admin or use the
sudo
along with the installation command above
To showcase HTMX's simplicity and directness, we'll build a task manager application that allows users to add tasks, view them, and mark them as completed by deleting them. This will help demonstrate HTMX’s ability to enhance HTML with minimal Javascript, in contrast with React’s component-based architecture and Javascript usage.
To set up the environment, you must first ensure we have Node.js installed. If you have that, then you can go ahead and create a new project and install the necessary packages using the following commands:
mkdir htmx-task-manager
cd htmx-task-manager
npm init -y
npm install express ejs body-parser
In the installation command above, we installed the following dependencies.
[express](https://www.npmjs.com/package/express)
: Express.js is a Next.js framework used for building RESTful APIs. [ejs](https://npmjs.com/package/ejs)
: This is a templating engine used for generating HTML on the server side.[body-parser](https://www.npmjs.com/package/body-parser)
: This is a Node.js library for extracting information from an HTTP request.Here's how our folder structure will look like. Proceed to create the various folders and files.
htmx-task-manager/
│
├── public/
│ └── style.css
├── views/
│ ├── index.html
│ └── partials/
│ └── task_list.html
├── app.js
└── package.json
The first thing is to set up the HTML basic structure the task manager. This will consist of a form for adding task and also a list to display them. Inside the views/index.html
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Task Manager</title>
<link rel="stylesheet" href="/style.css" />
<script src="https://unpkg.com/htmx.org@1.6.1"></script>
</head>
<body>
<h1>Task Manager</h1>
<form
hx-post="/add"
hx-target="#task-list-container"
hx-swap="innerHTML"
hx-on="htmx:afterRequest"
>
<input
type="text"
name="task"
placeholder="Enter a new task..."
required
/>
<button type="submit">Add Task</button>
</form>
<div id="task-list-container">
<% tasks.forEach(function(task) { %>
<div id="task-<%= task.id %>">
<%= task.task %>
<button
hx-post="/delete/<%= task.id %>"
hx-target="#task-list-container"
hx-swap="innerHTML"
>
Delete
</button>
</div>
<% }); %>
</div>
<script>
document.body.addEventListener("htmx:afterRequest", function (evt) {
if (evt.detail.elt.matches("form")) {
evt.detail.elt.reset();
}
});
</script>
</body>
</html>
NOTE: We loaded
HTMX
as a script inside thehead
element of the code.
In the code above, we created a form that will allow users to add new tasks to a task list. When a user submits the form, HTMX sends the POST request to the \add
endpoint on the server with the task details.
Once a response is received from the server, the content of the #task-list-container
div will be replaced with a newly returned task list. Which now contains the newly added task.
Next, inside the views/partials/task_list.html
, add the folowing code:
1
2
3
4
5
6
7
8
9
10
11
12
<% tasks.forEach(function(task) { %>
<div id="task-<%= task.id %>">
<%= task.task %>
<button
hx-post="/delete/<%= task.id %>"
hx-target="#task-list-container"
hx-swap="innerHTML"
>
Delete
</button>
</div>
<% }); %>
The code above generates a list of tasks, each corresponding with a “delete button”. When you click the button, you send a request to the server to remove the task, and the list is automatically updated to reflect the changes. This is due to HTMX’s ability to handle asynchronous requests and update the DOM accordingly.
Lastly, for our HTML structure, you need to add some styling. Inside the public/style.css
file, add the following styles:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 20px;
}
h1 {
color: #333;
}
form {
margin-bottom: 20px;
}
input[type="text"] {
padding: 10px;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 4px;
width: 300px;
}
button {
padding: 10px 20px;
border: none;
border-radius: 4px;
background-color: #007bff;
color: white;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
#task-list-container {
list-style-type: none;
padding: 0;
}
#task-list-container div {
display: flex;
justify-content: space-between;
align-items: center;
background-color: white;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
#task-list-container div button {
background-color: #dc3545;
border-color: #dc3545;
}
#task-list-container div button:hover {
background-color: #c82333;
}
Inside the app.js
file, add the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
let tasks = [];
app.engine("html", require("ejs").renderFile);
app.set("view engine", "html");
app.set("views", "./views");
app.use(express.static("public"));
// Serve static files from the public directory
// Render the main view with tasks
app.get("/", (req, res) => {
res.render("index", { tasks });
});
// Add a new task
app.post("/add", (req, res) => {
const task = req.body.task;
if (task) {
tasks.push({ id: tasks.length + 1, task: task });
}
res.render("partials/task_list", { tasks });
});
// Delete a task
app.post("/delete/:taskId", (req, res) => {
const taskId = parseInt(req.params.taskId, 10);
tasks = tasks.filter((task) => task.id !== taskId);
res.render("partials/task_list", { tasks });
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
In the code above, we are setting up a basic express server that listens to HTTP requests to manage the task lists. With this, users can add by sending a POST request to the \add
with the task details in the request body. They can also delete a task by sending a POST request to /delete/:taskId/
where :taskId
is the ID of the task to be deleted.
Finally, start your node app:
node app.js
Check the result in the browser:
Below is the link to the code on GitHub.
In this article, we discussed HTMX, what it entails, its features, and provided an example. We also compared it against React to see how it ranked.
Both libraries are a great choice when it comes to building modern applications. Choosing the right one for your project depends entirely on the requirements of your project.
I'm a web developer and writer. I love to share my experiences and things I've learned through writing.