<html>
<head>
<meta charset="UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
const { useState, useRef } = React;
function App() {
const [date, setDate] = useState('');
const handleInputChange = (e) => {
let inputDate = e.target.value;
// Remove non-numeric characters from the input
inputDate = inputDate.replace(/\D/g, '');
// Add hyphens to format the date as YYYY-MM-DD
if (inputDate.length <= 4) {
setDate(inputDate);
} else if (inputDate.length <= 6) {
setDate(`${inputDate.slice(0, 4)}-${inputDate.slice(4)}`);
} else if (inputDate.length <= 8) {
setDate(`${inputDate.slice(0, 4)}-${inputDate.slice(4, 6)}-${inputDate.slice(6)}`);
}
};
return (
<div className='container'>
<h3>React Input Mask Date YYYY-MM-DD</h3>
<label className='label'>Enter Date:</label>
<input
type="text"
placeholder="YYYY-MM-DD"
value={date}
onChange={handleInputChange}
maxLength="10"
className='input-class'
/>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
<style>
.container {
display: flex;
flex-direction: column;
align-items: center;
margin: 0 auto;
padding: 20px;
width: 600px;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
h3 {
color: #333;
}
.label-class {
display: block;
margin: 20px 0 10px;
font-weight: bold;
color: #555;
}
.input-class {
width: 100%;
height: 40px;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
outline: none;
transition: border-color 0.3s;
}
.input-class:focus {
border-color: #007bff;
}
/* Credit card number mask */
#creditCard {
letter-spacing: .5em;
}
</style>
</body>
</html>