MUI Textfield multiline by state (lost focus)

Viewed 526

I'm solving a problem regarding setting up a multi-line input after clicking on it. (in default is it single line) I have created a state that I set to true on the onFocus event (I set it to false on the onBlur event). The problem is that after clicking, I immediately lose focus of the input and have to click again. Is there any solution for this?

export default function App() {
  const [focus, setFocus] = React.useState(false);
  return (
    <TextField
      type="text"
      value="lollec asda sd asd as das "
      onFocus={() => setFocus(true)}
      onBlur={() => setFocus(false)}
      multiline={focus}
      rows={3}
    />
  );
}

Demo: https://codesandbox.io/s/hardcore-night-vhep1?file=/src/App.js

1 Answers

You can accomplish your described behavior by changing...

multiline={focus}
rows={3}

to...

multiline
rows={focus ? 3 : 1}

However, this introduces a scrollbar on the input when it's not focused. Additionally, clicking on the input will focus your cursor on the first line of text (where you clicked). You probably want the cursor to focus at the end of the text.

If you're fine with the cursor being on the first line, then I would just add some styles to hide the scrollbar.

If not, you're going to need to manage a ref for the input and specifically call ref.current.focus(). Typically, this would focus at the beginning of the text, though, so you'll need to take extra steps to ensure focus is at the end. Check out this question for help with that: Send cursor to the end of input value in React

Related