Reputation: 151
I'm trying to make my material ui textfield to accept the format of hh:mm:ss. What I mean is being able to change the numbers on hh mm and ss, while : are automatic. Any tips will be appreciated.
Upvotes: 1
Views: 537
Reputation: 5304
Use an onchange
and then don't allow non numerics and insert the colons:
import{ useState } from "react";
import TextField from "@mui/material/TextField";
function App() {
// TimeInput component defined inside App
const TimeInput = () => {
const [time, setTime] = useState("");
const handleTimeChange = (e) => {
let value = e.target.value;
// Remove any non-numeric characters except colons
value = value.replace(/[^0-9:]/g, "");
// Auto-insert colons
if (value.length === 2 || value.length === 5) {
value += value.endsWith(":") ? "" : ":";
}
// Limit length to 8 characters (hh:mm:ss)
value = value.slice(0, 8);
setTime(value);
};
return (
<TextField
label="Time (hh:mm:ss)"
value={time}
onChange={handleTimeChange}
placeholder="00:00:00"
/>
);
};
return (
<div className="App">
<h1>Time Input Example</h1>
<TimeInput />
</div>
);
}
export default App;
Here it is in code sandbox
Upvotes: 2
Reputation: 906
You need to create a custom field component something like TimestampField using a Grid
with three Input
Components of prop type="number"
.
<Grid container>
<Grid item xs={2.4}>
<TextField
type="number"
value={ 01 }
onChange={ (e) => { // validate e.target.value here } }
/>
</Grid>
<Grid item xs={2.4}>
:
</Grid>
<Grid item xs={2.4}>
<TextField
type="number"
value={ 01 }
/>
</Grid>
<Grid item xs={2.4}>
:
</Grid>
<Grid item xs={2.4}>
<TextField
type="number"
value={ 01 }
/>
</Grid>
</Grid>
Simple but the idea is correct, a different way of thinking.
Upvotes: 0