Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js - How to set a default value for input date type

Tags:

reactjs

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" />
like image 943
Abhinav Mehrotra Avatar asked Mar 14 '18 11:03

Abhinav Mehrotra


2 Answers

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

like image 136
kirecligol Avatar answered Sep 17 '22 10:09

kirecligol


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

2022 Answer

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>
like image 41
Stretch0 Avatar answered Sep 19 '22 10:09

Stretch0