I've been trying to learn React and I know my code structure is definitely not great but for some reason this code keeps outputting my letter I touch multiple times, it's as if its multiplying every tap I do, How can I fix this? I've been stuck on it for a couple hours now atleast and I just cant seem to figure it out even when I try to google it
Main content
import {useState} from 'react'
import './app.css'
import Guess from './Guess'
const guesses = [
[],
[],
[],
[],
[],
[]
]
const alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
function App(props) {
const count = 1
const [keyPressed, setKeyPressed] = useState("");
const keydownHandler = (event) => {
const letter = String.fromCharCode(event.keyCode)
if (alphabet.includes(letter)) {
guesses[0].push(letter)
setKeyPressed(letter)
}
}
document.addEventListener("keydown", keydownHandler)
return (
<>
<div className='title'>
<h1>Wordle Clone</h1>
<p>By: Brady Smith</p>
</div>
<div className="container">
{guesses.map((items, index) => {
return (
<ol>
{items.map((subItems, sIndex) => {
return <li> {subItems} </li>;
})}
</ol>
);
})}
<Guess letter={keyPressed}/>
<Guess />
<Guess />
<Guess />
<Guess />
<Guess />
</div>
</>
);
}
export default App;
Guess.js
import React, { useState } from 'react'
const Guess = ({letter}) => {
return (
<>
<div className="guess">
<div className="letter1">
<h1>{letter}</h1>
</div>
<div className="letter2">
<h1></h1>
</div>
<div className="letter3">
<h1></h1>
</div>
<div className="letter4">
<h1></h1>
</div>
<div className="letter5">
<h1></h1>
</div>
</div>
</>
)
}
export default Guess
CodePudding user response:
You have to subscribe to keyPress
function in every lifecycle.
useEffect(() => {
document.addEventListener("keydown", keydownHandler);
return () => document.removeEventListener("keydown", keydownHandler);
});