I would like to set the default date to be 3 days from todays date when the date picker opens up on the browser. How can I acheive that?
<input id="dateRequired" type="date" name="dateRequired" />
You need to convert the date to iso string and get first 10 characters. e.g.
var curr = new Date();
curr.setDate(curr.getDate() + 3);
var date = curr.toISOString().substr(0,10);
<input id="dateRequired" type="date" name="dateRequired" defaultValue={date} />
Reference toISOString method. Also you can see the result here
You need set the defaultValue attribute of the date input as yyyy-mm-dd
like so:
const today = new Date();
const numberOfDaysToAdd = 3;
const date = today.setDate(today.getDate() + numberOfDaysToAdd);
const defaultValue = new Date(date).toISOString().split('T')[0] // yyyy-mm-dd
<input id="dateRequired" type="date" name="dateRequired" defaultValue={defaultValue} />
Here is a working example: https://codesandbox.io/s/gracious-christian-22czv?file=/src/App.js:326-346
You can use toLocaleDateString with a locale to get the date string in yyyy-mm-dd
format.
class App extends React.Component {
render() {
const date = new Date();
const futureDate = date.getDate() + 3;
date.setDate(futureDate);
const defaultValue = date.toLocaleDateString('en-CA');
return (
<input id="dateRequired" type="date" name="dateRequired" defaultValue={defaultValue} />
);
}
}
ReactDOM.render(
<App />,
document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With