It is not clear where you want the date string to be outputted... So I assumed you wished it in in the state.
There are three cases in order to build the string, depending on which input changed. Additionally, you have to add the leading zeros.
I suggest you to apply the change handler on each inputs instead of the form. This will allow each inputs to be updated with the state value at each render allowing the leading zeros to be shown.
Have a look at the comments throughout the code.
function CustomDate() {
// Default state values
const inceptionValues = {
date: "2022-02-20",
hours: "00",
minutes: "00",
dateString: "2022-02-20T00:00:00"
};
// State hook
const [inceptionTest, setInceptionTest] = React.useState(inceptionValues);
// Add the leading zeros when necessary
const leadZero = (n) => {
return parseInt(n) < 10 ? `0${n}` : n;
};
// Change handler for the 3 inputs
// so e.target can be any of the 3 inputs
const handleChangeInception = (e) => {
let value = e.target.value;
let newdateString;
// Build the date string
if (e.target.name === "date") {
newdateString = `${value}T${inceptionTest.hours}:${inceptionTest.minutes}:00`;
}
if (e.target.name === "hours") {
value = leadZero(value);
newdateString = `${inceptionTest.date}T${value}:${inceptionTest.minutes}:00`;
}
if (e.target.name === "minutes") {
value = leadZero(value);
newdateString = `${inceptionTest.date}T${inceptionTest.hours}:${value}:00`;
}
// Prepare the object to set the new state
let newState = {
...inceptionTest,
[e.target.name]: value,
dateString: newdateString
};
console.log(newState);
setInceptionTest(newState);
};
// Render
return (
<form>
<input
style={{ margin: "0 5px 0 0" }}
type="date"
name="date"
value={inceptionTest.date}
onChange={(e) => handleChangeInception(e)}
/>
<input
style={{ border: "none" }}
type="number"
name="hours"
min="0"
max="23"
placeholder="23"
value={inceptionTest.hours}
onChange={(e) => handleChangeInception(e)}
/>
:
<input
style={{ border: "none" }}
type="number"
name="minutes"
min="0"
max="59"
placeholder="00"
value={inceptionTest.minutes}
onChange={(e) => handleChangeInception(e)}
/>
</form>
);
}
class App extends React.Component {
render() {
return (
<div className="App">
<h1>Custom date</h1>
<CustomDate />
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<div id="root"></div>