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

206
Visualizações
Material-ui Textfield loosing focus after re-rendering. How to fix it?

I am using Material-ui Textfield to represent repeatable array object:

const [sections, setSections] = useState([
    {
      Title: "Introduction",
      Text: ""
    },
    {
      Title: "Relationship",
      Text: ""
    },
    {
      Title: "Monitoring",
      Text: ""
    }
  ]);

I am rendering the sections with .map function. The problem is that I am using in my Textfields:

 <TextField
              value={el.Title}
              onChange={(event) => {
                el = { ...el, Title: event.target.value };
                sections[ind] = el;
                console.log(sections);
                return setSections([...sections]);
              }}
              variant="outlined"
              label={`Section ${ind + 1}`}
              style={{ margin: "auto" }}
            />

this onChange method. Each time I change someting in Textfield it looses focus. I am also using TextareaAutosize and same method for onChange:

<TextareaAutosize
              label="Message"
              variant="outlined"
              placeholder="Write here..."
              value={el.Text}
              onChange={(event) => {
                el = { ...el, Text: event.target.value };
                sections[ind] = el;
                console.log(sections);

                return setSections([...sections]);
              }}
              className={classes.messageStyle}
              style={{ width: "70%", marginLeft: "2.5%" }}
              minRows={5}
            />

But here I am NOT loosing focus and everything works perfectly fine. I found out that loosing focus is a result from re-rendering the sections after setting new state. This means TextField is assumed to be new component and that's why I loose focus. The questions is why with TextareaAutosize I do not face this issue and how I can fix it for TextField?

Here is the sandbox:

https://codesandbox.io/s/ancient-worker-td4bm?file=/src/App.js:1023-1239

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

0

enter image description here

Issue is here, on every render (title change) this key is getting changed, and react will consider it as a new element, so it will remove previous text contents inside that box and render new contents, so on every title change react is loading new text field that's why you loss its focus.

  {sections.map((el, ind) => (
        <Box
          key={ind}
          style={{
            width: "90%",
            margin: "0 auto"
          }}

this will solve your issue

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