Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

674
Visualizações
Unfocus/blur a Material UI input

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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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)

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda