Borislav Stefanov
Borislav Stefanov

Reputation: 731

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

Upvotes: 0

Views: 1247

Answers (1)

Sojin Antony
Sojin Antony

Reputation: 2217

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

Upvotes: 2

Related Questions