Build a Health Tracker Using Next.js
Last Updated :
05 Aug, 2024
A Health Tracker application allows users to add and monitor various health metrics such as weight, exercise, sleep, etc., and monitor their progress over time. This article will guide you through building a Health Tracker web application with features for adding, viewing, and updating health metrics using Next.js.
Prerequisites
Approach
- Initialize new project using npx create-next-app@latest.
- Implement the HealthTracker component, which will manage the logic for the health tracker system.
- Include a form to input health metrics such as weight, exercise, sleep, water intake, heart rate, blood pressure, blood sugar levels, and calories burned.
- Use the useState hook to manage the form state.
- Add a table to display all logged health metrics.
- Add functionality to edit and delete individual log entries.
Steps to Create a Health Tracker Using Next.js
Step 1: Create an application of NextJS using the following command.
npx create-next-app@latest health-tracker
Step 2: Navigate to the project directory
cd health-tracker
Step 3: Install the necessary package in your project using the following command.
npm install bootstrap
Project Structure
Project StructureDependencies
"dependencies": {
"react": "^18",
"bootstrap": "^5.3.3",
"react-dom": "^18",
"next": "14.2.5"
}
Example: This example shows the implementation of the above-explained approach.
JavaScript
// app.js
import React from "react";
import HealthTracker from "../app/components/Healthtracker";
function page() {
return (
<>
<HealthTracker />
</>
);
}
export default page;
JavaScript
// HealthTracker.js
"use client";
import { useState, useEffect } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
export default function HealthTracker() {
const [form, setForm] = useState({
weight: "",
exercise: "",
sleep: "",
water: "",
heartRate: "",
bloodPressure: "",
bloodSugar: "",
caloriesBurned: "",
});
const [logs, setLogs] = useState([]);
const [editIndex, setEditIndex] = useState(null);
const [error, setError] = useState("");
const handleChange = (e) => {
setForm({ ...form, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
// Validation: Check if all fields are filled
for (let key in form) {
if (form[key] === "") {
setError("All fields must be filled.");
return;
}
}
setError(""); // Clear any previous error message
const newLog = {
...form,
date: new Date().toISOString().split("T")[0],
};
if (editIndex !== null) {
const updatedLogs = logs.map((log, index) =>
index === editIndex ? newLog : log
);
setLogs(updatedLogs);
setEditIndex(null);
} else {
setLogs([...logs, newLog]);
}
setForm({
weight: "",
exercise: "",
sleep: "",
water: "",
heartRate: "",
bloodPressure: "",
bloodSugar: "",
caloriesBurned: "",
});
};
const handleEdit = (index) => {
setForm(logs[index]);
setEditIndex(index);
};
const handleDelete = (index) => {
const updatedLogs = logs.filter((_, i) => i !== index);
setLogs(updatedLogs);
};
const handleDeleteAll = () => {
setLogs([]);
};
useEffect(() => {
const savedLogs = JSON.parse(localStorage.getItem("logs") || "[]");
setLogs(savedLogs);
}, []);
useEffect(() => {
localStorage.setItem("logs", JSON.stringify(logs));
}, [logs]);
return (
<div className="container mt-4">
<h1>Health Tracker</h1>
<form onSubmit={handleSubmit}>
<div className="row mb-3">
<div className="col-12 col-md-6 col-lg-4">
<label className="form-label">Weight</label>
<input
type="number"
name="weight"
className="form-control"
value={form.weight}
onChange={handleChange}
/>
</div>
<div className="col-12 col-md-6 col-lg-4">
<label className="form-label">Exercise Duration (minutes)</label>
<input
type="number"
name="exercise"
className="form-control"
value={form.exercise}
onChange={handleChange}
/>
</div>
<div className="col-12 col-md-6 col-lg-4">
<label className="form-label">Sleep (hours)</label>
<input
type="number"
name="sleep"
className="form-control"
value={form.sleep}
onChange={handleChange}
/>
</div>
</div>
<div className="row mb-3">
<div className="col-12 col-md-6 col-lg-4">
<label className="form-label">Water Intake (liters)</label>
<input
type="number"
name="water"
className="form-control"
value={form.water}
onChange={handleChange}
/>
</div>
<div className="col-12 col-md-6 col-lg-4">
<label className="form-label">Heart Rate (bpm)</label>
<input
type="number"
name="heartRate"
className="form-control"
value={form.heartRate}
onChange={handleChange}
/>
</div>
<div className="col-12 col-md-6 col-lg-4">
<label className="form-label">Blood Pressure (mmHg)</label>
<input
type="text"
name="bloodPressure"
className="form-control"
value={form.bloodPressure}
onChange={handleChange}
/>
</div>
</div>
<div className="row mb-3">
<div className="col-12 col-md-6 col-lg-4">
<label className="form-label">Blood Sugar Levels (mg/dL)</label>
<input
type="number"
name="bloodSugar"
className="form-control"
value={form.bloodSugar}
onChange={handleChange}
/>
</div>
<div className="col-12 col-md-6 col-lg-4">
<label className="form-label">Calories Burned</label>
<input
type="number"
name="caloriesBurned"
className="form-control"
value={form.caloriesBurned}
onChange={handleChange}
/>
</div>
</div>
{error && <div className="alert alert-danger">{error}</div>}
<button type="submit" className="btn btn-primary">
{editIndex !== null ? "Update" : "Submit"}
</button>
</form>
<h2 className="mt-4">Monitor Progress</h2>
{logs.length > 0 ? (
<div className="table-responsive">
<table className="table">
<thead>
<tr>
<th>Date</th>
<th>Weight</th>
<th>Exercise Duration</th>
<th>Sleep</th>
<th>Water Intake</th>
<th>Heart Rate</th>
<th>Blood Pressure</th>
<th>Blood Sugar Levels</th>
<th>Calories Burned</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{logs.map((entry, index) => (
<tr key={index}>
<td>{entry.date}</td>
<td>{entry.weight}</td>
<td>{entry.exercise}</td>
<td>{entry.sleep}</td>
<td>{entry.water}</td>
<td>{entry.heartRate}</td>
<td>{entry.bloodPressure}</td>
<td>{entry.bloodSugar}</td>
<td>{entry.caloriesBurned}</td>
<td>
<button
className="btn btn-warning me-2"
onClick={() => handleEdit(index)}
>
Edit
</button>
<button
className="btn btn-danger"
onClick={() => handleDelete(index)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<p>No logs to display</p>
)}
</div>
);
}
Start your application using the following command.
npm run dev
Output:
Similar Reads
Expense Tracker using Next.js The Expense Tracker project is a NextJS-based web application designed to help users manage their finances more effectively. Users can easily add and delete expenses and income, allowing them to track their spending habits and view a summary of their expenses. This project not only provides a practi
4 min read
Health Tracker App Backend Using Node and Express.js A Health Tracker App is a platform that allows users to log and monitor various data of their health and fitness. In this article, we are going to develop a Health Tracker App with Node.js and Express.js. that allows users to track their health-related activities such as exercise, meals, water intak
4 min read
Build a News Portal Using Next.js In this article, we will explore how to build a news portal using Next.js, a popular React framework for server-side rendering and static site generation. The news portal will allow users to publish and categorize news articles, providing a seamless user experience with fast page loads and dynamic c
8 min read
Health Tracker using MERN Stack In this step-by-step guide, we'll walk through the process of building a Health Tracker application using React for the frontend and Node for the backend. This application allows users to track their health metrics such as steps taken, calories burned, distance covered, and more.Preview of final out
10 min read
Health Tracker using MEAN Stack In the fast-paced world, maintaining a healthy lifestyle is more important than ever. Technology can play a significant role in helping individuals monitor and improve their health. In this article, we'll explore how to use the power of the MEAN (MongoDB, Express.js, Angular, Node.js) stack to build
15+ min read