score:1

This is my solution. I handle when the card will display by check if the input has already 4 characters length and then add space in it.

The important part is when you type each character you have to remove all old space before add space again otherwise it will fill the input with a lot of weird space.

Here is my code. You can see its action here

import React, { useState } from 'react';

function App() {
    const [card, setCard] = useState('')

    const handleCardDisplay = () => {
        const rawText = [...card.split(' ').join('')] // Remove old space
        const creditCard = [] // Create card as array
        rawText.forEach((t, i) => {
            if (i % 4 === 0) creditCard.push(' ') // Add space
            creditCard.push(t)
        })
        return creditCard.join('') // Transform card array to string
    }

    return (
        <div>
            <input 
                value={handleCardDisplay()} 
                onChange={(e) => setCard(e.target.value)}
            />
        </div>
    )
}

export default App;


Related Query

More Query from same tag