To implement a dynamic form with date and time pickers in Next.js, you can utilize various libraries available. One popular choice is using react-datepicker
for handling date and time inputs. Here's a step-by-step guide on how to implement it:
Install Required Packages:
Start by installing the necessary packages using npm or yarn. In this case, you'll need react-datepicker
.
bashnpm install react-datepicker
# or
yarn add react-datepicker
Create the Form Component:
Create a new component for your dynamic form. For example, DynamicForm.js
.
jsximport React, { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
const DynamicForm = () => {
const [startDate, setStartDate] = useState(new Date());
return (
<form>
<div>
<label htmlFor="name">Name:</label>
<input type="text" id="name" />
</div>
<div>
<label htmlFor="email">Email:</label>
<input type="email" id="email" />
</div>
<div>
<label htmlFor="dob">Date of Birth:</label>
<DatePicker selected={startDate} onChange={(date) => setStartDate(date)} />
</div>
<div>
<label htmlFor="appointment">Appointment Time:</label>
<DatePicker
selected={startDate}
onChange={(date) => setStartDate(date)}
showTimeSelect
dateFormat="MMMM d, yyyy h:mm aa"
/>
</div>
<button type="submit">Submit</button>
</form>
);
};
export default DynamicForm;
Use the Form Component:
Now, you can use this DynamicForm
component in your Next.js pages.
jsx// pages/index.js
import React from 'react';
import DynamicForm from '../components/DynamicForm';
const Home = () => {
return (
<div>
<h1>Dynamic Form Example</h1>
<DynamicForm />
</div>
);
};
export default Home;
Styling (Optional): You might want to add some CSS to style your form according to your design requirements.
That's it! Now you have a dynamic form with date and time pickers in your Next.js application. You can further customize it according to your specific needs.