Creating a well-structured, professional React application with Tailwind CSS involves several steps. Below, I'll guide you through building a React app with three main pages: Sign In, Register (multi-step), and Verification. We'll use React Router for navigation, Axios for API calls, and Tailwind CSS for styling.
Project Structure
my-app/
├── public/
├── src/
│ ├── components/
│ │ ├── SignIn.jsx
│ │ ├── Register.jsx
│ │ ├── Verification.jsx
│ │ └── MultiStepForm/
│ │ ├── Step1.jsx
│ │ ├── Step2.jsx
│ │ └── Step3.jsx
│ ├── services/
│ │ └── api.js
│ ├── App.jsx
│ ├── index.css
│ └── index.js
├── tailwind.config.js
├── package.json
└── ...other files
1. Setup the React Project with Tailwind CSS
First, initialize your React project and install the necessary dependencies.
npx create-react-app my-app
cd my-app
# Install React Router, Axios, and Tailwind CSS
npm install react-router-dom axios
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Configure tailwind.config.js by setting the content paths:
// tailwind.config.js
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
Add Tailwind directives to src/index.css:
/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
2. Setting Up Routing in App.jsx
We'll use react-router-dom to handle navigation between pages.
// src/App.jsx
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import SignIn from './components/SignIn';
import Register from './components/Register';
import Verification from './components/Verification';
function App() {
return (
<Router>
<div className="min-h-screen bg-gray-100">
<Routes>
<Route path="/" element={<SignIn />} />
<Route path="/register/*" element={<Register />} />
<Route path="/verify" element={<Verification />} />
</Routes>
</div>
</Router>
);
}
export default App;
3. Creating the API Service
Create a centralized API service using Axios for handling HTTP requests.
// src/services/api.js
import axios from 'axios';
const API_BASE_URL = 'https://your-api-url.com/api'; // Replace with your actual API base URL
const api = axios.create({
baseURL: API_BASE_URL,
});
// Interceptor to add token to headers if available
api.interceptors.request.use((config) => {
const token = localStorage.getItem('token'); // Adjust based on your storage strategy
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
}, (error) => Promise.reject(error));
export const signIn = (identifier, password) => {
return api.post('/signin', { identifier, password });
};
export const registerUser = (userData) => {
return api.post('/register', userData);
};
export const verifyEmail = (token) => {
return api.post('/verify-email', { token });
};
export default api;
4. Building the SignIn Component
A simple sign-in form that authenticates the user and stores the token.
// src/components/SignIn.jsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { signIn } from '../services/api';
function SignIn() {
const [identifier, setIdentifier] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const navigate = useNavigate();
const handleSignIn = async (e) => {
e.preventDefault();
try {
const response = await signIn(identifier, password);
localStorage.setItem('token', response.data.token); // Adjust as needed
navigate('/dashboard'); // Redirect to a protected route or homepage
} catch (err) {
setError(err.response?.data?.message || 'Sign in failed');
}
};
return (
<div className="flex items-center justify-center h-screen bg-blue-50">
<form onSubmit={handleSignIn} className="bg-white p-8 rounded shadow-md w-full max-w-md">
<h2 className="text-2xl mb-6 text-center">Sign In</h2>
{error && <div className="mb-4 text-red-500">{error}</div>}
<div className="mb-4">
<label className="block mb-1">Identifier</label>
<input
type="text"
value={identifier}
onChange={(e) => setIdentifier(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
placeholder="Username or Email"
/>
</div>
<div className="mb-6">
<label className="block mb-1">Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
placeholder="Your password"
/>
</div>
<button type="submit" className="w-full bg-blue-500 text-white py-2 rounded hover:bg-blue-600">
Sign In
</button>
<p className="mt-4 text-center">
Don't have an account? <a href="/register" className="text-blue-500">Register</a>
</p>
</form>
</div>
);
}
export default SignIn;
5. Creating the Multi-Step Register Component
The registration process involves multiple steps: Username, Email, Password. We'll use React Router's nested routes to handle each step.
5.1. Register.jsx
// src/components/Register.jsx
import React from 'react';
import { Routes, Route, useNavigate } from 'react-router-dom';
import Step1 from './MultiStepForm/Step1';
import Step2 from './MultiStepForm/Step2';
import Step3 from './MultiStepForm/Step3';
import { registerUser } from '../services/api';
function Register() {
const navigate = useNavigate();
// Store registration data in state
const [formData, setFormData] = React.useState({
username: '',
email: '',
password: '',
});
const handleNext = (data) => {
setFormData({ ...formData, ...data });
};
const handleSubmit = async () => {
try {
const response = await registerUser(formData);
localStorage.setItem('token', response.data.token);
navigate('/dashboard'); // Redirect after registration
} catch (err) {
console.error(err);
// Handle errors accordingly
}
};
return (
<div className="flex items-center justify-center h-screen bg-green-50">
<div className="bg-white p-8 rounded shadow-md w-full max-w-md">
<Routes>
<Route path="/" element={<Step1 next={handleNext} />} />
<Route path="/email" element={<Step2 next={handleNext} />} />
<Route path="/password" element={<Step3 submit={handleSubmit} />} />
</Routes>
</div>
</div>
);
}
export default Register;
5.2. Step1.jsx (Username)
// src/components/MultiStepForm/Step1.jsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
function Step1({ next }) {
const [username, setUsername] = useState('');
const navigate = useNavigate();
const handleContinue = (e) => {
e.preventDefault();
next({ username });
navigate('/register/email');
};
return (
<form onSubmit={handleContinue}>
<h2 className="text-2xl mb-6 text-center">Register - Step 1</h2>
<div className="mb-4">
<label className="block mb-1">Username</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
placeholder="Choose a username"
/>
</div>
<button type="submit" className="w-full bg-green-500 text-white py-2 rounded hover:bg-green-600">
Next
</button>
</form>
);
}
export default Step1;
5.3. Step2.jsx (Email)
// src/components/MultiStepForm/Step2.jsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
function Step2({ next }) {
const [email, setEmail] = useState('');
const navigate = useNavigate();
const handleContinue = (e) => {
e.preventDefault();
next({ email });
navigate('/register/password');
};
return (
<form onSubmit={handleContinue}>
<h2 className="text-2xl mb-6 text-center">Register - Step 2</h2>
<div className="mb-4">
<label className="block mb-1">Email</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
placeholder="Your email address"
/>
</div>
<button type="submit" className="w-full bg-green-500 text-white py-2 rounded hover:bg-green-600">
Next
</button>
</form>
);
}
export default Step2;
5.4. Step3.jsx (Password)
This step includes password validation checks.
// src/components/MultiStepForm/Step3.jsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
function Step3({ submit }) {
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [errors, setErrors] = useState([]);
const navigate = useNavigate();
const validatePassword = () => {
const validationErrors = [];
if (password.length < 8) validationErrors.push('Password must be at least 8 characters.');
if (!/[A-Z]/.test(password)) validationErrors.push('Password must contain a capital letter.');
if (!/[a-z]/.test(password)) validationErrors.push('Password must contain a lowercase letter.');
if (!/[0-9]/.test(password)) validationErrors.push('Password must contain a number.');
if (password !== confirmPassword) validationErrors.push('Passwords do not match.');
return validationErrors;
};
const handleSubmit = (e) => {
e.preventDefault();
const validationErrors = validatePassword();
if (validationErrors.length > 0) {
setErrors(validationErrors);
return;
}
// If validation passes, proceed
submit({ password });
// Optionally navigate to a success page
};
return (
<form onSubmit={handleSubmit}>
<h2 className="text-2xl mb-6 text-center">Register - Step 3</h2>
{errors.length > 0 && (
<div className="mb-4 text-red-500">
<ul>
{errors.map((err, idx) => <li key={idx}>{err}</li>)}
</ul>
</div>
)}
<div className="mb-4">
<label className="block mb-1">Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
placeholder="Create a password"
/>
</div>
<div className="mb-6">
<label className="block mb-1">Confirm Password</label>
<input
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
placeholder="Confirm your password"
/>
</div>
<button type="submit" className="w-full bg-green-500 text-white py-2 rounded hover:bg-green-600">
Register
</button>
</form>
);
}
export default Step3;
6. Creating the Verification Component
This page takes a token from the query parameters, sends it to the verification endpoint, and displays the result.
// src/components/Verification.jsx
import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { verifyEmail } from '../services/api';
function useQuery() {
return new URLSearchParams(useLocation().search);
}
function Verification() {
const query = useQuery();
const token = query.get('token');
const [status, setStatus] = useState('Verifying...');
useEffect(() => {
const verify = async () => {
try {
const response = await verifyEmail(token);
setStatus(response.data.message);
} catch (err) {
setStatus(err.response?.data?.message || 'Verification failed');
}
};
if (token) {
verify();
} else {
setStatus('No verification token provided.');
}
}, [token]);
return (
<div className="flex items-center justify-center h-screen bg-purple-50">
<div className="bg-white p-8 rounded shadow-md w-full max-w-md text-center">
<h2 className="text-2xl mb-4">Email Verification</h2>
<p>{status}</p>
{status === 'Email verified successfully' && (
<a href="/" className="mt-4 inline-block text-blue-500">Go to Sign In</a>
)}
</div>
</div>
);
}
export default Verification;
7. Additional Considerations
7.1. Protected Routes
If you have routes that require authentication, you can create a ProtectedRoute component.
// src/components/ProtectedRoute.jsx
import React from 'react';
import { Navigate } from 'react-router-dom';
function ProtectedRoute({ children }) {
const token = localStorage.getItem('token');
if (!token) {
return <Navigate to="/" replace />;
}
return children;
}
export default ProtectedRoute;
Use it in App.jsx:
// ... other imports
import ProtectedRoute from './components/ProtectedRoute';
import Dashboard from './components/Dashboard'; // Example protected component
function App() {
return (
<Router>
<div className="min-h-screen bg-gray-100">
<Routes>
<Route path="/" element={<SignIn />} />
<Route path="/register/*" element={<Register />} />
<Route path="/verify" element={<Verification />} />
<Route
path="/dashboard"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>
{/* Add other protected routes similarly */}
</Routes>
</div>
</Router>
);
}
7.2. Handling Token Expiration and Logout
Implement logic to handle token expiration and provide a logout mechanism.
// Example Logout button component
// src/components/LogoutButton.jsx
import React from 'react';
import { useNavigate } from 'react-router-dom';
function LogoutButton() {
const navigate = useNavigate();
const handleLogout = () => {
localStorage.removeItem('token');
navigate('/');
};
return (
<button onClick={handleLogout} className="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600">
Logout
</button>
);
}
export default LogoutButton;
8. Styling with Tailwind CSS
Ensure all components utilize Tailwind's utility classes for a consistent and responsive design. Tailwind allows you to rapidly build custom designs without leaving your HTML. Here's an example of a button:
<button class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
Click Me
</button>
Feel free to customize colors, spacing, and other utilities as per your design requirements. You can also extend Tailwind's theme in tailwind.config.js to add custom colors, fonts, etc.
9. Running the Application
Start your React application with:
npm start
Ensure your backend API is running and accessible at the specified API_BASE_URL. Adjust CORS settings if necessary to allow requests from your React frontend.
10. Final Notes
-
Security: Avoid storing tokens in localStorage for sensitive applications due to XSS vulnerabilities. Consider using HTTP-only cookies for better security.
-
Error Handling: Enhance error handling to cover various edge cases and provide more user-friendly feedback.
-
Form Libraries: For more complex forms, consider using form libraries like Formik or React Hook Form for better state management and validation.
-
State Management: For larger applications, integrating a state management library like Redux might be beneficial.
-
Responsive Design: Ensure all components are responsive for a good user experience across different devices.
By following this guide, you should have a solid foundation for your React application with authentication and email verification features, styled elegantly with Tailwind CSS. Customize and expand upon this base to fit the specific needs of your project.