React type tester only receiving one input then stopping

Viewed 26

So I'm not sure why my code isn't taking into subsequent keydowns, it takes the first 'l' then just stops:

I honestly don't know what the issue is. The lorem is a long string that I turn into an array, then if "e.key" === array item at 0, remove that item and update position.

I don't know why this isn't being done for every keydown.

import { useState } from "react"

const Input = ({text}) => {
    const [lorem,changeString] = useState(text.split(''))
    const [input,changeInput] = useState('')
    const [position,changePosition] = useState(0)
    const [color,changeColor] = useState(false)

    const keyDown = (e) => {
        changeInput(e.key)
        compareCharacters(input)
    }

    const compareCharacters = (input) => {
        if (input === lorem[position]) {
            changeString(lorem.splice(0,1))
            changePosition(position+1)
        } else {
            changeColor(true)
        }
    }


  return (
    <input className={`text ${color ? 'new' : ''}`}
    type="text" 
    size="10000"
    onKeyDown={keyDown}
    >
    </input>
  )
}

export default Input
1 Answers
import { useState } from 'react'

const Input = ({ text }) => {
  const [lorem, changeString] = useState(text.split(''))
  const [position, changePosition] = useState(0)
  const [color, changeColor] = useState(false)

  const keyDown = (e) => {
    if (e.key !== lorem[position]) {
      changeColor(true)
      return
    }
    changeString(lorem.slice(1))
    changePosition(position + 1)
  }



  return (
    <input
      className={`text ${color ? 'new' : ''}`}
      type="text"
      size={10000}
      onKeyDown={keyDown}
    ></input>
  )
}

export default Input
Related