javascriptreactjsreact-hooksmaterial-uiuse-state

MUI Custom Text Field loses focus on state change


I'm using MUI library to create my React Js app.

Here I'm using the controlled Text Field component to create a simple search UI.

But there is something strange. The Text Field component loses focus after its value is changed. This is my first time facing this problem. I never faced this problem before.

How this could happen? And what is the solution.

Here is the code and the playground: https://codesandbox.io/s/mui-autocomplete-lost-focus-oenoo?

Note: if I remove the breakpoint type from the code, the Text Field component still loses focus after its value is changed.


Solution

  • It's because you're defining a component inside another component, so that component definition is recreated every time the component renders (and your component renders every time the user types into the input).

    Two solutions:

    1. Don't make it a separate component.

      Instead of:

      const MyComponent = () => {
        const MyInput = () => <div><input /></div>; // you get the idea
      
        return (
          <div>
            <MyInput />
          </div>
        );
      };
      

      Do:

      const MyComponent = () => {    
        return (
          <div>
            <div><input /></div> {/* you get the idea */}
          </div>
        );
      };
      
    2. Define the component outside its parent component:

      const MyInput = ({value, onChange}) => (
        <div>
          <input value={value} onChange={onChange} />
        </div>
      );
      
      const MyComponent = () => {
        const [value, setValue] = useState('');
      
        return (
          <div>
            <MyInput
              value={value}
              onChange={event => setValue(event.target.value)}
            />
          </div>
        );
      };