To create a login page for a React application, you will need to use React components to create the page's layout and form elements. You can then use React's onChange event to track input from the user, and React's state to store the entered information. When the user submits the form, you can use React's onSubmit event to handle the login request and either redirect the user to the protected page or display an error message if the login fails.
import React, { useState } from 'react';
function LoginPage() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [errorMessage, setErrorMessage] = useState('');
function handleSubmit(event) {
event.preventDefault();
// Check the entered username and password against your database or authentication service
if (username === 'test' && password === 'password') {
// Redirect the user to the protected page
window.location.href = '/protected';
} else {
// Display an error message if the login fails
setErrorMessage('Invalid username or password.');
}
}
return (
<form onSubmit={handleSubmit}>
{errorMessage && <p className="error">{errorMessage}</p>}
<label>
Username:
<input
type="text"
value={username}
onChange={(event) => setUsername(event.target.value)}
/>
</label>
<label>
Password:
<input
type="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
</label>
<button type="submit">Login</button>
</form>
);
}
In this example, the LoginPage component uses React's useState hook to store the entered username and password, as well as any error messages that need to be displayed. The handleSubmit function is called when the user submits the form, and it checks the entered username and password against a database or authentication service. If the login is successful, the user is redirected to the protected page. If the login fails, an error message is displayed.
Top comments (0)