Solution
To set value in input type date in React, pass your date into value
attribute of input type date. it will show your pass date as a selected date.
To format a date you can read my below article, here I have explained multiple ways to format a date.
https://reactjssnippet.com/posts/how-to-display-date-in-react-js/
Snippet
In this snippet, we will see short example to set value in input type date.
<input
type="date"
onChange={(e) => setDate(e.target.value)}
value={"2023-01-01"}
/>
Example
In this example, we will write a react js code to set value in input type date.
Note: Before set date into in input type date you have to format it into YYYY-MM-DD
.
Below Example is using moment
to format date.
Let’s list down what we are going to do below example.
- Create
date
state where we will store input type date value - Set Yesterday date into input type date
- Show selected
date
into React UI.
import React, { useState, useEffect } from "react";
import moment from "moment";
export default function App() {
const [date, setDate] = useState("");
useEffect(() => {
// yesterday Date
const date = new Date().setDate(new Date().getDate() - 1);
setDate(moment(date).format("YYYY-MM-DD"));
}, []);
return (
<div className="App">
<input
type="date"
onChange={(e) => setDate(e.target.value)}
value={date}
/>
<h3>Selected Date</h3>
<p>{date}</p>
</div>
);
}
Output