Unfocus/blur a Material UI input

Viewed 3985

I have an input field that can be reset/cleared by a button click:

https://codesandbox.io/s/basictextfields-material-demo-forked-m1z5l?file=/demo.js:127-482

  const searchInput = useRef(null);

  const clearInput = () => {
    searchInput.current.value = '';
    searchInput.current.blur();
  }

  return (
    <div>
      <Input
        inputRef={searchInput} 
        id="outlined-basic" 
        label="Outlined" 
        variant="outlined" />
      <button onClick={clearInput}>Clear</button>
    </div>
  );

The issue is that the label does not reset to it's original position after clearing the input. I'm guessing because the input field still thinks it has the focus. I tried adding a blur() but that doesn't seem to do anything.

4 Answers

This is in no way an elegant solution. But it's what I got to make it work as you wanted

import React, {useRef, useState, } from 'react';
import Input from '@mui/material/TextField';

export default function BasicTextFields() {
  const searchInput = useRef(null);
  const [isFocused, setFocus] = useState(false);

  const clearInput = () => {
    searchInput.current.value = '';
    searchInput.current.blur();
    setInputFocus(false)
  }

  const setInputFocus = (state)=>{
    const notEmpty = !!searchInput.current?.value;

    if(notEmpty) return setFocus(true)

    setFocus(state)
  }

  return (
    <div>
      <Input
        inputRef={searchInput} 
        id="outlined-basic" 
        label="Outlined" 
        InputLabelProps={{shrink: isFocused}}
        onFocus={()=>setInputFocus(true)}
        onBlur={()=>setInputFocus(false)}
        variant="outlined" />
      <button onClick={clearInput}>Clear</button>
    </div>
  );
}

Edit BasicTextFields Material Demo (forked)

If what you really want is clearing the TextField programmatically, then just use controlled mode and reset the value state when needed. See uncontrolled-vs-controlled:

export default function BasicTextFields() {
  const [value, setValue] = useState("");
  const clearInput = () => setValue("");

  return (
    <>
      <Input
        value={value}
        onChange={(e) => setValue(e.target.value)}
        label="Outlined"
        variant="outlined"
      />
      <button onClick={clearInput}>Clear</button>
    </>
  );
}

Live Demo

Codesandbox Demo

You can use inputProps for catch onBlur event.

    <Input
        id="outlined-basic" 
        label="Outlined" 
        variant="outlined"
        inputProps={{
            onBlur: () => {
                console.log('foo bar')
            }
        }}/>
      <button onClick={clearInput}>Clear</button>

If you are using TextField, then you just have to use onBlur property:

  <TextField
    onBlur={your_method_handleOnBlur}
    ...other props
  />
Related