Search code examples
reactjsdatepicker

How do I disable future dates in reactjs?


I have not use any datepicker still code is working fine. I have selected input type to date and everything's working fine. Now I want to disable future dates. How do I do that?

<div className="form-group col-md-6">
                            <label for="inputDate4">Date of Birth</label>
                            <input type="date" className="form-control" id="inputDate4" placeholder="Date of Birth" name="dob" onChange={this.handleChange} />
                        </div>

Edit: Issue solve by other way

I used React Date Picker

It is so easy to implement. Just install the npm package

npm install react-datepicker --save

Install moment aslo

npm install moment --save

Import the libraries

import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';

In the constructor

this.state = {
      dob: moment()
    };
    this.dateChange = this.dateChange.bind(this);

dateChange function

dateChange(date) {
    this.setState({
      dob: date
    });
  }

And finally the render function

 <DatePicker
     selected={this.state.dob}
     onChange={this.dateChange}
     className="form-control"
    placeholder="Date of Birth"
    maxDate={new Date()}
    />

Here the maxDate function is used to disable future dates.

maxDate={new Date()}

Source: https://www.npmjs.com/package/react-datepicker

Thank you!


Solution

  • You can use a min, max attribute to restrict the date selection within a date range

    <div className="form-group col-md-6">
         <label for="inputDate4">Date of Birth</label>
         <input type="date" className="form-control" id="inputDate4" placeholder="Date of Birth" name="dob" onChange={this.handleChange} max={moment().format("YYYY-MM-DD")}/>
    </div>