I have an API that returns the dates in a string format as shown below. How to set the value of the input type date to this value?
let str = "2020-1-1"
<input type= "date" value = {value} />
CodePudding user response:
You will have to format the date into YYYY-MM-DD
before passing it to the date input.
To do this, you can use:
const str = "29/11/2020";
const [day, month, year] = str.split('/');
const date = `${year}-${month}-${day}`;
<input type="date" value={date} />
CodePudding user response:
To provide a value to the input field of type date
you pass value in this format yyyy-mm-dd
so regarding you question you should update your date value like this 2021-11-29
CodePudding user response:
let str = "29/11/2021";
let dateEl = document.getElementById("date");
let value = str.split('/').reverse().join('-');
dateEl.value = value;
<input id="date" type= "date" />
CodePudding user response:
That will one possible solution:
const str = "29/11/2020";
const [day, month, year] = str.split('/');
document.getElementById('date').value = `${year}-${month}-${day}`
<input id="date" type= "date" />
CodePudding user response:
if you use simple HTML and JavaScript than provide id
attribute to input element and assign value on time when you receive data from api
<input id='some_unique_id' type= "date" />
and on Javascript side use document methods to get element and set value of element
const element = document.getElementById('some_unique_id');
element.value = 'your date value'
and if you are using React with functions components than use useState
hook
import React, { useState } from 'react'
const [value, setValue] = useState(null);
and for html side
<input value={value} />
you can call
setValue('any value you want')
to set value from where you get api response.
or if you use classes
in React bcz hooks only work in functional components.
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
dateValue: new Date()
};
}
render() {
return (
<div>
<input value={this.state.dateValue} />
</div>
);
}
}
you can update state from where you call api and get data like
this.setState({ dateValue: 'your api date value' })