Reputation: 83
In REact I am having a state variable like this
const [ dob, setDob ] = useState();
and in the jsx I am having like this
<input type="date" max="new Date()" value = {dob} onChange={(e)=>setDov(e.target.value)}/>
I am facing two issues
new Date() or new Date().getTime()
Notes:- I am using React and purely functional components
Upvotes: 0
Views: 710
Reputation: 2558
If you look at the MDN docs for date type and constraining the inputs, you can use min
and max
attributes on input. So what you did is right except passing a string to max. It needs to be a string (parsable to date) or date object I think.
e.g.
<input type="date" max={new Date()} value = {dob} onChange={(e)=>setDov(e.target.value)}/>
Refer - https://developer.mozilla.org/en-US/docs/Learn/Forms/HTML5_input_types#constraining_datetime_values for more details.
Upvotes: 1
Reputation: 809
You have multiple error/problem in the code:
1- You can't add JS code in html variable, the HTML max
property accept texts. and another issue you had there (event if max accepts JS expression) is that new Date ()
dosen't match the format it accepts, you have to convert it ISO standard i.e. new Date().toISOString()
.
2- I am not sure whats the issue you are facing here, belwo I added a snippest that worked for me, that resolved both (1 and 2).
const [ dob, setDob ] = useState();
const today = new Date().toISOString();
return (
<div >
<input type="date" max={today} value = {dob} onChange={(e)=>setDob(e.target.value)}/>
</div>
);
Upvotes: 0