Reputation: 4033
I am trying to hide a div
when typing into an input field. The functionality I am looking for is to hide the div when typing and to unhide it if all input is backspaced.
My problem is when I type one letter it hides but on the next key press it shows. I am struggling to find an event handler that doesn't toggle the "TEST" div
(I have tried a few of these). Can I do it with an event handler or do I need to work on a more specific function?
JS:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [isTyping, setIsTyping] = useState(true);
const hide = () => setIsTyping(!isTyping);
return (
<div className="App">
First name: <input type="text" name="fname" onKeyPress={hide} />
<br />
<br />
<div className={isTyping ? "block" : "hide"}> TEST </div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
I am new to react and am still working out the kinks.
Upvotes: 1
Views: 62
Reputation: 29
Not sure this will work, but hopefully this might give you an idea! (NOT REACT GUY) https://codesandbox.io/s/busy-knuth-7hs4z
Upvotes: 0
Reputation: 2955
I think you can do it like this:
function App() {
const [value, setValue] = useState('');
const storeValue = (e) => setValue(e.target.value || '');
return (
<div className="App">
First name: <input type="text" value={value} name="fname" onChange={storeValue} />
<br />
<br />
<div className={value.length === 0 ? "block" : "hide"}> TEST </div>
</div>
);
}
Here is the updated link: https://codesandbox.io/s/stoic-mendel-bo9i1?fontsize=14
Upvotes: 1