Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lost input focus on hooks function state change

When i define the hooks state in the parent function i lost input field focus on first key press. I need the state definition in the root function.

import React, { useState } from 'react'

function Test1(props) {
    const [test, setTest] = useState({value1: "", value2:""});

    const Test = () => {

        const handleChange= (e) => {
            const _test = {...test, [e.target.name]: e.target.value}
            setTest(_test)
        }

        return (
            <div style={{ margin: "200px" }}>
                <input name="value1" value={test["value1"]} onChange={handleChange}></input>
                <input name="value2" value={test["value2"]} onChange={handleChange}></input>
                <button onClick={() => console.log(test)}>Console.Log</button>
            </div>
        )
    }


    return (
        <Test />
    );

}


export default Test1;

But if I move the state definition in to the child function it works.


import React, { useState } from 'react'

function Test1(props) {

    const Test = () => {
        const [test, setTest] = useState({value1: "", value2:""});

        const handleChange= (e) => {
            const _test = {...test, [e.target.name]: e.target.value}
            setTest(_test)
        }

        return (
            <div style={{ margin: "200px" }}>
                <input name="value1" value={test["value1"]} onChange={handleChange}></input>
                <input name="value2" value={test["value2"]} onChange={handleChange}></input>
                <button onClick={() => console.log(test)}>Console.Log</button>
            </div>
        )
    }


    return (
        <Test />
    );

}


export default Test1;

So! Why is this happening and how can I get over it?

like image 228
Unsal Avatar asked Apr 12 '19 14:04

Unsal


People also ask

Why does the input field lose focus after typing a character?

it is because you are rendering the form in a function inside render(). Every time your state/prop change, the function returns a new form. it caused you to lose focus.

How do I change my state in Hooks?

To update the state, call the state updater function with the new state setState(newState) . Alternatively, if you need to update the state based on the previous state, supply a callback function setState(prevState => newState) .

Do React Hooks replace state?

Hooks are a more direct way to use the React features you already know — such as state, lifecycle, context, and refs. They don't fundamentally change how React works, and your knowledge of components, props, and top-down data flow is just as relevant.


1 Answers

I have been seeing this pattern a lot where people nest components in methods in components. It may be an opinion, but I feel like this may not be a great pattern.

I would abstract the one component function and pass the props down to the 2nd. something like this

const Test = ({test, setTest}) => {

  const handleChange= (e) => {
      const _test = {...test, [e.target.name]: e.target.value}
      setTest(_test)
  }

  return (
      <div style={{ margin: "200px" }}>
          <input name="value1" value={test["value1"]} onChange={handleChange}></input>
          <input name="value2" value={test["value2"]} onChange={handleChange}></input>
          <button onClick={() => console.log(test)}>Console.Log</button>
      </div>
  )
}

function Test1(props) {
    const [test, setTest] = useState({value1: "", value2:""});


    return (
        <Test test={test} setTest={setTest} />
    );

}


export default Test1;

like image 165
Beaulne Avatar answered Oct 19 '22 23:10

Beaulne