Abhinav Mehrotra
Abhinav Mehrotra

Reputation: 613

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

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 achieve that?

<input id="dateRequired" type="date" name="dateRequired" />

Upvotes: 33

Views: 91211

Answers (5)

Nassim
Nassim

Reputation: 447

Create a helper function that returns the correct format of the <input type="date" /> which is yyyy-mm-dd.

Let's define a function:

const getCurrentDateInput = () => {

  const dateObj = new Date();

  // get the month in this format of 04, the same for months
  const month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
  const day = ("0" + dateObj.getDate()).slice(-2);
  const year = dateObj.getFullYear();

  const shortDate = `${year}-${month}-${day}`;

  return shortDate;
};

Then go back to the input tag and type the following :

<input type="date" defaultValue={getCurrentDateInput()}  />

Upvotes: 3

thinkerBOB
thinkerBOB

Reputation: 176

Declare a state :-

this.state={ 
   recentDate:new Date().toISOString().slice(0,10)
}

Declare a function by means of which you can also be able select different dates.

selectedDate(e){    
     this.setState({recentDate:e.target.value})    
}

Call the state into value attribute and selectedDate function in onChange prop.

<input 
    type="date" 
    value={this.state.rencentDate} 
    onChange={this.selectedDate} 
 />

Upvotes: 2

kirecligol
kirecligol

Reputation: 876

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().substring(0,10);
<input id="dateRequired" type="date" name="dateRequired" defaultValue={date} /> 

Reference toISOString method. Also you can see the result here

Upvotes: 46

Stretch0
Stretch0

Reputation: 9251

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>

Upvotes: 20

mikolaj semeniuk
mikolaj semeniuk

Reputation: 2458

2022 Answer

using jsx

import { useState } from 'react'

const Component = () => {
    
    let defaultDate = new Date()
    defaultDate.setDate(defaultDate.getDate() + 3)

    const [date, setDate] = useState(defaultDate)

    const onSetDate = (event) => {
        setDate(new Date(event.target.value))
    }

    return (
        <>
            <p>date: {date.toString()}</p>
            <p>date: {date.toLocaleDateString('en-CA')}</p>
            <input type="date" value={date.toLocaleDateString('en-CA')} onChange={onSetDate} />
        </>
    )
}

export default Component

using tsx

import { useState } from "react"

const Component = (): JSX.Element => {
    
    let defaultDate = new Date()
    defaultDate.setDate(defaultDate.getDate() + 3)

    const [date, setDate] = useState<Date>(defaultDate)

    const onSetDate = (event: React.ChangeEvent<HTMLInputElement>): void => {
        setDate(new Date(event.target.value))
    }

    return (
        <>
            <p>date: {date.toString()}</p>
            <p>date: {date.toLocaleDateString('en-CA')}</p>
            <input type="date" value={date.toLocaleDateString('en-CA')} onChange={onSetDate} />
        </>
    )
}

export default Component

Upvotes: 4

Related Questions