Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
onFocus and onBlur events for multiple elements

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>
  );
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
 }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!