This is continuation to my previous post, I am going to explain how we can rewrite the previous application using functional state setter.
Follow below step-by-step procedure to build the Application.
Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘user-registration-with-functional-state-setter’.
Project structure looks like below.
Step 2: Create components folder in src folder and define UserRegistration component.
UserRegistration.jsx
import { useState } from "react";
export default function UserRegistration() {
const [userDetails, setUserDetails] = useState({
myName: "",
myEmail: "",
disableRegistration: true,
});
function handleNameChange(event) {
setUserDetails((prevState) => ({
...prevState,
myName: event.target.value,
disableRegistration: !event.target.value || !prevState.myEmail,
}));
}
function handleEmailChange(event) {
setUserDetails((prevState) => ({
...prevState,
myEmail: event.target.value,
disableRegistration: !prevState.myName || !event.target.value,
}));
}
function registerUser(event) {
event.preventDefault();
console.log(JSON.stringify(userDetails));
}
return (
<form method="POST" onSubmit={registerUser}>
<label forname="username">Enter Username : </label>
<input
type="text"
id="username"
value={userDetails.myName}
onChange={handleNameChange}
/>
<br />
<br />
<label forname="email">Enter Email : </label>
<input
type="email"
id="email"
value={userDetails.myEmail}
onChange={handleEmailChange}
/>
<br />
<br />
<button disabled={userDetails.disableRegistration}>Register</button>
</form>
);
}
Step 3: Update main.jsx file like below.
main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import UserRegistration from './components/UserRegistration'
createRoot(document.getElementById('root')).render(
<StrictMode>
<UserRegistration />
</StrictMode>,
)
Step 4: Build and run the Application by executing below commands.
cd user-registration-with-functional-state-setter npm install npm run dev
Open the url ‘http://localhost:5173/’ in browser, you will see below kind of screen.
Experiment with the above application by entering username and email, you can see the entered details in console post Registration.
You can download this application from this link.
No comments:
Post a Comment