I'm trying to handle the onFocus and onBlur events for 2 elements - the input and the textarea elements. I even tried to implement it as one state with the object but it's just not possible, so I separated it into two states. Whenever I try to focus on the textarea, it'll expand, however, if I start focusing on the input element, it'll collapse instead of staying expanded. How do I implement this?
const [titleFocused, setTitleFocus] = useState(null);
const [contentFocused, setContentFocus] = useState(null);
function handleFocus(event) {
const {name} = event.target;
setTitleFocus(name === 'title' && true);
setContentFocus(name === 'content' && true);
}
function handleUnfocus(event) {
const {name} = event.target;
setTitleFocus(name === 'title' && false);
setContentFocus(name === 'content' && false);
}
return (
<div >
<form
className="create-note">
{titleFocused || contentFocused && (
<input
name="title"
onChange={handleChange}
value={note.title}
placeholder="Title"
onFocus={handleFocus}
onBlur={handleUnfocus}
/>)
}
<textarea
name="content"
onChange={handleChange}
value={note.content}
placeholder="Take a note..."
onFocus={handleFocus}
onBlur={handleUnfocus}
rows={titleFocused || contentFocused ? "3" : "1"}
/>
<Zoom in={titleFocused || contentFocused} appear={true}>
<Fab onClick={submitNote}>
<AddIcon fontSize="large" />
</Fab>
</Zoom>
</form>
</div>
);
Probably caused by event handles toggling both states even when the event is not concerning the component.
This should work
function handleFocus(event) {
const {name} = event.target;
name === 'title' && setTitleFocus(true);
name === 'content' && setContentFocus(true);
}
function handleUnfocus(event) {
const {name} = event.target;
name === 'title' && setTitleFocus(false);
name === 'content' && setContentFocus( false);
}