I'm trying to manipulate the DOM based on what's being typed (text
) in an input in a React component:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function App() {
const [text, setText] = useState("Initial value");
function handleChange(event) {
setText(event.target.value);
}
useEffect(() => {
function handleKeypress(event) {
console.log("text", text);
// do something with the DOM with text
}
document.addEventListener("keydown", handleKeypress);
return () => {
document.removeEventListener("keydown", handleKeypress);
};
}, [text]);
return (
<div id="keys">
<input type="text" onChange={handleChange} value={text} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
It works, but something strange happens. text
won't change unless keydown
is triggered a second time.
For example, if you press a
, console.log("text", text)
will log Initial value
. It won't log a
. I think there's some kind of delay.
Why is this? And how to change the code so that console.log("text", text)
logs the key that's being pressed?
Live code: https://codesandbox.io/s/react-hooks-useeffect-forked-sfujxi?file=/src/index.js
Note: The reason I'm using the event listener is that I want the code to also run when, for example, I press Ctrl + Key
(in that situation text
doesn't change).