Search code examples
reactjsreact-componentreact-functional-component

why Input field returned by a react component function goes out of focus on each key


when I create a function to return a JSX input field in react, the cursor goes out of focus on each key, meaning i can enter one character and then I have to click on the input field again to enter another character, can someone explain whats going on and how i can prevent this or doing this in react is not advisable? my code:

import React, {useState} from 'react';

export default function App(props) {
   const [value, setValue] = useState();

   const Show = () => {
     return (
        <div>
            <input type="text" name="name" value={value} onChange={(e) => setValue(e.target.value)}/>
        </div>
    )
  }



   return (
       <Show></Show>
   );
}

Solution

  • Because you've defined a component within a function.

    Every time App re-renders, its really a new function call. This means Show is redefined. It's completely destroyed and re-created. The result is that every re-render, <Show/> is re-mounted. The input will lose focus on a component re-mount.

    Do not declare components within other components. There is no benefit, only drawbacks.

    Assuming your actual use-case does have a reason for separating the input from the rest of the return JSX, you could call it as a function instead of a component. Make the const lowercase, and instead of <Show></Show> return show(). The state variables will remain in scope, but it will no longer be a component, just a function that returns JSX.

    Otherwise I would recommend putting it outside the App function and passing in your state value and updater through props.