Creating a comprehensive single-page web application as per your specifications involves several steps. Below, I'll guide you through setting up the project, configuring Tailwind CSS, and implementing all the required functionalities using React.js. We'll also utilize some additional libraries to enhance the app's capabilities, such as axios for HTTP requests and recharts for dynamic, responsive charts.
Table of Contents
- Project Setup
- Installing Dependencies
- Configuring Tailwind CSS
- Implementing the Application
- Final Touches
- Complete Code
Project Setup
First, ensure that you have Node.js installed on your machine. We'll use create-react-app for bootstrapping the project.
npx create-react-app url-ping-monitor
cd url-ping-monitor
Installing Dependencies
We'll install the necessary dependencies:
- Tailwind CSS: For styling.
- axios: For making HTTP requests.
- recharts: For rendering dynamic charts.
- react-icons: For adding icons (optional but enhances UI).
- classnames: For conditional class rendering.
Install them using npm or yarn:
# Using npm
npm install axios recharts react-icons classnames
# Using yarn
yarn add axios recharts react-icons classnames
Configuring Tailwind CSS
Set up Tailwind CSS by following its official installation guide. Here's a quick setup:
-
Install Tailwind CSS and its dependencies:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
-
Configure tailwind.config.js:
// tailwind.config.js
module.exports = {
purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
-
Add Tailwind directives to src/index.css:
/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
-
Ensure index.css is imported in src/index.js:
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Implementing the Application
Now, let's implement the application step-by-step.
1. Setting Up the Main Components
We'll structure the app with the following main components:
- App: The root component.
- PingForm: Handles user input for URL and interval selection.
- PingChart: Displays the ping results graphically.
- PingHistory: (Optional) Shows a table of ping results.
App Component
// src/App.js
import React, { useState, useEffect, useRef } from 'react';
import PingForm from './components/PingForm';
import PingChart from './components/PingChart';
import axios from 'axios';
function App() {
const [url, setUrl] = useState('');
const [intervalTime, setIntervalTime] = useState(30000); // default 30s
const [pings, setPings] = useState([]);
const intervalRef = useRef(null);
// Load from local storage on mount
useEffect(() => {
const savedUrl = localStorage.getItem('url') || '';
const savedInterval = parseInt(localStorage.getItem('intervalTime')) || 30000;
const savedPings = JSON.parse(localStorage.getItem('pings')) || [];
setUrl(savedUrl);
setIntervalTime(savedInterval);
setPings(savedPings);
}, []);
// Persist to local storage whenever URL, intervalTime, or pings change
useEffect(() => {
localStorage.setItem('url', url);
localStorage.setItem('intervalTime', intervalTime);
localStorage.setItem('pings', JSON.stringify(pings));
}, [url, intervalTime, pings]);
// Function to perform a single ping
const performPing = async () => {
if (!url) return;
const startTime = Date.now();
try {
const response = await axios.get(url, { timeout: intervalTime - 1000 });
const timeTaken = Date.now() - startTime;
const pingResult = {
timestamp: new Date(),
status: response.status,
time: timeTaken,
};
setPings(prev => [...prev, pingResult].slice(-50)); // Keep last 50 pings
} catch (error) {
const timeTaken = Date.now() - startTime;
const pingResult = {
timestamp: new Date(),
status: error.response ? error.response.status : 'Error',
time: timeTaken,
};
setPings(prev => [...prev, pingResult].slice(-50));
}
};
// Start pinging at the selected interval
const startPinging = () => {
if (intervalRef.current) clearInterval(intervalRef.current);
performPing(); // Immediate ping
intervalRef.current = setInterval(performPing, intervalTime);
};
// Stop pinging
const stopPinging = () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
};
// Handle form submission
const handleSubmit = (inputUrl, selectedInterval) => {
setUrl(inputUrl);
setIntervalTime(selectedInterval);
startPinging();
};
// Cleanup on unmount
useEffect(() => {
return () => clearInterval(intervalRef.current);
}, []);
return (
<div className="min-h-screen bg-gray-100 p-4">
<div className="max-w-4xl mx-auto">
<h1 className="text-3xl font-bold text-center mb-6">URL Ping Monitor</h1>
<PingForm onSubmit={handleSubmit} initialUrl={url} initialInterval={intervalTime} />
<div className="mt-8 bg-white p-6 rounded shadow">
<PingChart pings={pings} />
</div>
</div>
</div>
);
}
export default App;
2. Creating the URL Input Form
The PingForm component captures the user's input for the URL and the desired interval.
// src/components/PingForm.js
import React, { useState } from 'react';
const PingForm = ({ onSubmit, initialUrl, initialInterval }) => {
const [url, setUrl] = useState(initialUrl);
const [interval, setInterval] = useState(initialInterval);
const handleSubmit = (e) => {
e.preventDefault();
if (!url) {
alert('Please enter a valid URL.');
return;
}
onSubmit(url, parseInt(interval));
};
return (
<form onSubmit={handleSubmit} className="bg-white p-6 rounded shadow">
<div className="flex flex-col md:flex-row md:items-end md:space-x-4">
<div className="flex-1 mb-4 md:mb-0">
<label className="block text-gray-700 mb-2">URL:</label>
<input
type="url"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://example.com"
required
className="w-full px-3 py-2 border rounded"
/>
</div>
<div className="mb-4 md:mb-0">
<label className="block text-gray-700 mb-2">Interval:</label>
<select
value={interval}
onChange={(e) => setInterval(e.target.value)}
className="w-full px-3 py-2 border rounded"
>
<option value={30000}>30 Seconds</option>
<option value={60000}>1 Minute</option>
<option value={180000}>3 Minutes</option>
<option value={300000}>5 Minutes</option>
</select>
</div>
<div>
<button
type="submit"
className="w-full md:w-auto px-6 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
>
Start Pinging
</button>
</div>
</div>
</form>
);
};
export default PingForm;
3. Implementing the Ping Logic
The ping logic is primarily handled within the App component. Here's a brief explanation:
- performPing: Makes an HTTP GET request to the specified URL using
axios. It records the response status and the time taken for the request.
- startPinging: Initializes the pinging process using
setInterval.
- stopPinging: Clears the interval to stop pinging.
- useEffect Hooks: Load and persist data using local storage.
4. Displaying the Ping Results with Recharts
We'll use recharts to create a dynamic, real-time updating chart that visualizes the ping results.
// src/components/PingChart.js
import React from 'react';
import {
LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, Dot
} from 'recharts';
import { format } from 'date-fns';
const PingChart = ({ pings }) => {
// Prepare data for the chart
const data = pings.map((ping, index) => ({
name: format(new Date(ping.timestamp), 'HH:mm:ss'),
status: ping.status,
time: ping.time,
index: index,
}));
// Determine color based on status
const getColor = (status) => {
if (status >= 200 && status < 300) return '#22c55e'; // Green
if (status >= 300 && status < 400) return '#3b82f6'; // Blue
if (status >= 400 && status < 500) return '#f97316'; // Orange
if (status >= 500) return '#ef4444'; // Red
return '#6b7280'; // Gray for 'Error' or unknown
};
// Custom tooltip
const CustomTooltip = ({ active, payload, label }) => {
if (active && payload && payload.length) {
const ping = pings[parseInt(label.split(':')[2])]; // Extract index
return (
<div className="bg-white border p-2 rounded shadow">
<p><strong>Time:</strong> {format(new Date(ping.timestamp), 'PPpp')}</p>
<p><strong>Status:</strong> {ping.status}</p>
<p><strong>Response Time:</strong> {ping.time} ms</p>
</div>
);
}
return null;
};
// Custom dot to change color based on status
const renderCustomDot = (props) => {
const { cx, cy, payload } = props;
if (cx === undefined || cy === undefined) return null;
return (
<circle
cx={cx}
cy={cy}
r={4}
fill={getColor(payload.status)}
stroke="#fff"
strokeWidth={1}
/>
);
};
return (
<div>
<h2 className="text-xl font-semibold mb-4">Ping Results</h2>
{pings.length === 0 ? (
<p className="text-gray-500">No data to display. Start pinging a URL!</p>
) : (
<ResponsiveContainer width="100%" height={300}>
<LineChart data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" interval="preserveStartEnd" />
<YAxis domain={['auto', 'auto']} label={{ value: 'ms', angle: -90, position: 'insideLeft' }}/>
<Tooltip content={<CustomTooltip />} />
<Line
type="monotone"
dataKey="time"
stroke="#8884d8"
dot={renderCustomDot}
activeDot={{ r: 8 }}
/>
</LineChart>
</ResponsiveContainer>
)}
</div>
);
};
export default PingChart;
Explanation:
- Data Preparation: Transforms the ping data into a format suitable for
recharts.
- Color Coding: Assigns colors to each data point based on the HTTP status code.
- Custom Tooltip: Displays detailed information when hovering over a data point.
- Custom Dots: Changes the color of each dot on the line chart based on the ping's status.
5. Persisting Data with Local Storage
The App component already handles persisting the URL, interval, and ping history using localStorage. This ensures that the user's settings and ping history persist across page reloads.
Final Touches
To enhance the application's usability and appearance:
- Responsive Design: Ensure that the app looks good on various screen sizes.
- Error Handling: Provide user feedback for invalid URLs or network issues.
- Notifications: Optionally, implement notifications for significant events (like a failed ping).
Complete Code
Below is the complete code for the application, organized by file structure.
1. package.json
Ensure your package.json includes the necessary dependencies.
{
"name": "url-ping-monitor",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^1.4.0",
"classnames": "^2.3.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^4.10.1",
"recharts": "^2.5.0",
"react-scripts": "5.0.1",
"tailwindcss": "^3.3.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build"
},
// ... other configurations
}
2. tailwind.config.js
// tailwind.config.js
module.exports = {
purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
3. src/index.css
/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
4. src/index.js
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
5. src/App.js
// src/App.js
import React, { useState, useEffect, useRef } from 'react';
import PingForm from './components/PingForm';
import PingChart from './components/PingChart';
import axios from 'axios';
function App() {
const [url, setUrl] = useState('');
const [intervalTime, setIntervalTime] = useState(30000); // default 30s
const [pings, setPings] = useState([]);
const intervalRef = useRef(null);
// Load from local storage on mount
useEffect(() => {
const savedUrl = localStorage.getItem('url') || '';
const savedInterval = parseInt(localStorage.getItem('intervalTime')) || 30000;
const savedPings = JSON.parse(localStorage.getItem('pings')) || [];
setUrl(savedUrl);
setIntervalTime(savedInterval);
setPings(savedPings);
}, []);
// Persist to local storage whenever URL, intervalTime, or pings change
useEffect(() => {
localStorage.setItem('url', url);
localStorage.setItem('intervalTime', intervalTime);
localStorage.setItem('pings', JSON.stringify(pings));
}, [url, intervalTime, pings]);
// Function to perform a single ping
const performPing = async () => {
if (!url) return;
const startTime = Date.now();
try {
const response = await axios.get(url, { timeout: intervalTime - 1000 });
const timeTaken = Date.now() - startTime;
const pingResult = {
timestamp: new Date(),
status: response.status,
time: timeTaken,
};
setPings(prev => [...prev, pingResult].slice(-50)); // Keep last 50 pings
} catch (error) {
const timeTaken = Date.now() - startTime;
const pingResult = {
timestamp: new Date(),
status: error.response ? error.response.status : 'Error',
time: timeTaken,
};
setPings(prev => [...prev, pingResult].slice(-50));
}
};
// Start pinging at the selected interval
const startPinging = () => {
if (intervalRef.current) clearInterval(intervalRef.current);
performPing(); // Immediate ping
intervalRef.current = setInterval(performPing, intervalTime);
};
// Stop pinging
const stopPinging = () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
};
// Handle form submission
const handleSubmit = (inputUrl, selectedInterval) => {
setUrl(inputUrl);
setIntervalTime(selectedInterval);
startPinging();
};
// Cleanup on unmount
useEffect(() => {
return () => clearInterval(intervalRef.current);
}, []);
return (
<div className="min-h-screen bg-gray-100 p-4">
<div className="max-w-4xl mx-auto">
<h1 className="text-3xl font-bold text-center mb-6">URL Ping Monitor</h1>
<PingForm onSubmit={handleSubmit} initialUrl={url} initialInterval={intervalTime} />
<div className="mt-8 bg-white p-6 rounded shadow">
<PingChart pings={pings} />
</div>
</div>
</div>
);
}
export default App;
6. src/components/PingForm.js
// src/components/PingForm.js
import React, { useState } from 'react';
const PingForm = ({ onSubmit, initialUrl, initialInterval }) => {
const [url, setUrl] = useState(initialUrl);
const [interval, setInterval] = useState(initialInterval);
const handleSubmit = (e) => {
e.preventDefault();
if (!url) {
alert('Please enter a valid URL.');
return;
}
onSubmit(url, parseInt(interval));
};
return (
<form onSubmit={handleSubmit} className="bg-white p-6 rounded shadow">
<div className="flex flex-col md:flex-row md:items-end md:space-x-4">
<div className="flex-1 mb-4 md:mb-0">
<label className="block text-gray-700 mb-2">URL:</label>
<input
type="url"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://example.com"
required
className="w-full px-3 py-2 border rounded"
/>
</div>
<div className="mb-4 md:mb-0">
<label className="block text-gray-700 mb-2">Interval:</label>
<select
value={interval}
onChange={(e) => setInterval(e.target.value)}
className="w-full px-3 py-2 border rounded"
>
<option value={30000}>30 Seconds</option>
<option value={60000}>1 Minute</option>
<option value={180000}>3 Minutes</option>
<option value={300000}>5 Minutes</option>
</select>
</div>
<div>
<button
type="submit"
className="w-full md:w-auto px-6 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
>
Start Pinging
</button>
</div>
</div>
</form>
);
};
export default PingForm;
7. src/components/PingChart.js
// src/components/PingChart.js
import React from 'react';
import {
LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, Dot
} from 'recharts';
import { format } from 'date-fns';
const PingChart = ({ pings }) => {
// Prepare data for the chart
const data = pings.map((ping, index) => ({
name: format(new Date(ping.timestamp), 'HH:mm:ss'),
status: ping.status,
time: ping.time,
index: index,
}));
// Determine color based on status
const getColor = (status) => {
if (typeof status === 'number') {
if (status >= 200 && status < 300) return '#22c55e'; // Green
if (status >= 300 && status < 400) return '#3b82f6'; // Blue
if (status >= 400 && status < 500) return '#f97316'; // Orange
if (status >= 500) return '#ef4444'; // Red
}
return '#6b7280'; // Gray for 'Error' or unknown
};
// Custom tooltip
const CustomTooltip = ({ active, payload, label }) => {
if (active && payload && payload.length) {
const index = payload[0].payload.index;
const ping = pings[index];
return (
<div className="bg-white border p-2 rounded shadow">
<p><strong>Time:</strong> {format(new Date(ping.timestamp), 'PPpp')}</p>
<p><strong>Status:</strong> {ping.status}</p>
<p><strong>Response Time:</strong> {ping.time} ms</p>
</div>
);
}
return null;
};
// Custom dot to change color based on status
const renderCustomDot = (props) => {
const { cx, cy, payload } = props;
if (cx === undefined || cy === undefined) return null;
return (
<circle
cx={cx}
cy={cy}
r={4}
fill={getColor(payload.status)}
stroke="#fff"
strokeWidth={1}
/>
);
};
return (
<div>
<h2 className="text-xl font-semibold mb-4">Ping Results</h2>
{pings.length === 0 ? (
<p className="text-gray-500">No data to display. Start pinging a URL!</p>
) : (
<ResponsiveContainer width="100%" height={300}>
<LineChart data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" interval="preserveStartEnd" />
<YAxis domain={['auto', 'auto']} label={{ value: 'ms', angle: -90, position: 'insideLeft' }}/>
<Tooltip content={<CustomTooltip />} />
<Line
type="monotone"
dataKey="time"
stroke="#8884d8"
dot={renderCustomDot}
activeDot={{ r: 8 }}
/>
</LineChart>
</ResponsiveContainer>
)}
</div>
);
};
export default PingChart;
Running the Application
After setting up all the files, you can run the application using:
npm start
or
yarn start
This will start the development server, and you can view the application by navigating to http://localhost:3000 in your web browser.
Additional Enhancements
To make your application even more robust and user-friendly, consider implementing the following:
- Validation of URLs: Ensure that the entered URL is valid and reachable before starting the ping process.
- Pause/Resume Functionality: Allow users to pause and resume the pinging without clearing the history.
- Historical Data Export: Provide an option to export the ping history as a CSV or JSON file.
- Responsive Design Enhancements: Fine-tune the UI to ensure optimal usability across all devices.
- Error Logging: Implement detailed error logging for network issues or unexpected errors.
- Advanced Analytics: Show metrics like average response time, number of successful/failed pings, etc.
By following this guide, you now have a fully functional single-page web application that monitors a user's specified URL at defined intervals, displays the status and response times graphically, and persists data using local storage. The combination of React.js and Tailwind CSS ensures a responsive and modern user interface, while recharts provides dynamic and interactive data visualization.
Feel free to customize and expand upon this foundation to better suit your specific needs!