Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextField mui component autoFocus end of text

Right now, autoFocus applies to the beginning of the input but I'd like to get focused on the end of the text.

export default function BasicTextFields() {
  const [value, setValue] = React.useState(
    "hello world. hello world. hello world"
  );

  return (
    <Box
      component="form"
      sx={{
        "& > :not(style)": { m: 1, width: "25ch" }
      }}
      noValidate
      autoComplete="off"
    >
      <TextField
        id="outlined-basic"
        variant="outlined"
        value={value}
        onChange={(e) => setValue(e.target.value)}
        multiline
        autoFocus
      />
    </Box>
  );
}

Is this possible?

I tried this from this link : https://github.com/mui/material-ui/issues/12779 But this didn't work for my case.

<TextField
    variant="outlined"
    type="text"
    id="field-comment"
    name="comment"
    label="Label"
    placeholder="Placeholder"
    onChange={(event) => setValue(event.target.value)}
    inputRef={(input) => input && input.focus()}
    onFocus={(e) =>
        e.currentTarget.setSelectionRange(
        e.currentTarget.value.length,
        e.currentTarget.value.length
    )}
    multiline
    rows={4}
    value={value}
    className={classes.sCommentTextField}
/>

I also tried this.

<TextField
  inputRef={input => input && input.focus()}
/>

but it also didn't work.

Are there any ways that I can do this?

like image 747
Happy1234 Avatar asked Oct 19 '25 03:10

Happy1234


1 Answers

This works!

<TextField
    variant="outlined"
    type="text"
    id="field-comment"
    name="comment"
    label="Label"
    placeholder="Placeholder"
    onChange={(event) => setValue(event.target.value)}
    inputRef={(input) => input && input.focus()}
    onFocus={(e) =>
        e.currentTarget.setSelectionRange(
        e.currentTarget.value.length,
        e.currentTarget.value.length
    )}
    multiline
    rows={4}
    value={value}
    className={classes.sCommentTextField}
/>

Remove autoFocus and add inputRef and onFocus

like image 127
Happy1234 Avatar answered Oct 20 '25 17:10

Happy1234