I want to create the input string where a user can input an expire date of his bank card. I would like the values in the input string look like “MM/YY” and after pressing a key each of the subsquent values (M then M then Y and one more Y) changes to the key, that user pressed
I did try this code, but ran into difficulties
import React, { useState, useRef} from 'react';
function ExpireDate() {
const [expireDate, setExpireDate] = useState([])
const handleExpireDate = event => {
const keyPressed = event.key
if (!/d/.test(keyPressed)) {
if (keyPressed === 'Backspace') {
setExpireDate((prev) => {
const newValue = [...prev]
newValue.pop()
return newValue;
})
}
return;
}
setExpireDate((prev) => {
if (prev.length >=2) {
return prev;
}
const newValue = [...prev]
newValue.push(keyPressed)
return newValue;
})
}
const formattedExpireDate = (expireDate) => {
console.log(`Expire date is: ${JSON.stringify(expireDate)}`)
const month = new Array(2 - expireDate.length).fill('M').join('')
const displayExpireDate = (expireDate.join('') + month)
.replace(/(.{1,2})/, '$1/')
return displayExpireDate;
}
return (
<div>
<div>
<br />
<input
className={`expire-date`}
value={formattedExpireDate(expireDate)}
onChange={() => {}}
onKeyDown={handleExpireDate}
size='5'
placeholder=''
/>
</div>
</div>
)
}
export default ExpireDate;
New contributor
Нікіта Гончарук is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.