6

I have TextField with a helperText. I want to make the helperText span multiple lines. For that I needs some kind of line break. Material-UI renders <p>{ helperText }</p>. Since in html line breaks in paragraphs are given by <br/> I tried to add that to my text. This however just adds the <br/> into the text. I also tried defining the helperText outside the component, once with the <br/> and once with \n. But that didn't work either.

How do I properly add a line break into the helperText?

Example of my code:

<TextField
    name={"help message"}
    value={data_field.helper_text}
    onChange={(event) => handleDataChange("helper_text", event.target.value)}
    helperText={"The value will be shown be shown below the field, just like this text is.<br> This <br/> text should go in the second line."}
/>

Example of result:

enter image description here

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
ChocolateRain
  • 203
  • 2
  • 9

1 Answers1

9

helperText props can accept a ReactNode, so you can add a <br/> element to break into newline like this:

<TextField
  fullWidth
  helperText={
    <>
      The value will be shown be shown below the field, just like this text
      is.
      <br />
      This
      <br /> text should go in the second line.
    </>
  }
  {...props}
/>

Edit 67264236/textfield-helpertext-spanning-multiple-lines

Another solution as suggested by @Vaibhav is to set a width on the element that contains helperText:

import { styled } from '@mui/material/styles';
import MuiTextField from '@mui/material/TextField';

const TextField = styled(MuiTextField)({
  '& .MuiFormHelperText-root': {
    width: 250,
  },
});
<TextField
  fullWidth
  helperText="The value will be shown be shown below the field, just like this text is. This text should go in the second line."
  label="Outlined"
  variant="outlined"
/>

Edit 67264236/textfield-helpertext-spanning-multiple-lines (forked)

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230