Home > front end >  Expand the input box TextField to fullWidth when selected in Material UI with React?
Expand the input box TextField to fullWidth when selected in Material UI with React?

Time:10-25

I'm working on a Material UI form where the input box (Text Field) is 200px wide on load.

I want to make the input box expand to 100% width only when the box is selected or clicked on.

...
<FormGroup sx={{ maxWidth: "200px" }}>
        <FormControl>
          <TextField
            id="first_name"
            label="First name" />
        </FormControl>
</FormGroup> 
...

I'm looking to doing something like How to stretch input field to full width? but with Material UI.

I've tried using an onClick attribute on TextField but that did not action register an event on click.

I know there's a fullWidth attribute for TextField but I'm just not sure how to go about changing the attribute on click.

CodePudding user response:

Remove width from FormGroup and add inside TextField then override css class with 100% width. You can also add transition property if you want to increase the width smoothly than instant.

...
<FormGroup>
  <FormControl>
    <TextField
      sx={{
        width: 200,
        '&:focus-within':{
          width:'100%',
        },
        transition: 'width 1s',
      }}
      id="first_name"
      label="First name"
    />
  </FormControl>
</FormGroup> 
...
  • Related