1

I would like the defaultValue of a TextField to show "Username" upon page render. onFocus, I would like "Username" to disappear so that the user may comfortably type. I tried the following:

function Login() {
  const [usernameDefaultValue, setUsernameDefaultValue] = useState("Username");

  return (    <div>
        <TextField
          required
          id="standard-required"
          label="Required"
          defaultValue={usernameDefaultValue}
          onFocus={() => setUsernameDefaultValue('')}
          variant="standard"
        />

)}

but as it is currently the user must double-click the defaultValue ("Username") in order to clear the field for their actual username.

Michael
  • 169
  • 3
  • 11
  • 2
    Just a curiosity. Why don't you set usernameDefaultValue to "" or undefined and use a placeholder with the value "Username" such as ? – Magofoco Feb 24 '22 at 01:13
  • I tried that, but if I use "placeholder" it shifts (or omits, i can't remember which) the "required" field – Michael Feb 24 '22 at 01:50
  • You can try this for the label/placeholder issue: https://stackoverflow.com/questions/70624192/how-to-show-both-label-and-placeholder-in-material-ui-textfield/70626286 – Magofoco Feb 24 '22 at 01:51

1 Answers1

0

No need for temporary values to be controlled by state when using this library. This is what the label prop is there for. Set the label to "Username" and set the state separately, with an initial value of ''

function Login() {
  const [userName, setUserName] = useState('')

  const handleChange = (e) => {
    const name = e.target.value

    return setUserName(name)
  }

  return (
    <TextField
       id="standard-required"
       label="Username"
       onChange={handleChange}
       required 
       value={userName}
       variant="standard"
    />
  )
}