skip to Main Content

I’m using Material-UI Grid to layout two TextField components side-by-side in a responsive form, with each intended to take up 50% of the parent’s width. However, the TextFields don’t stretch properly and appear smaller than expected. Here’s the code I’m working with:

import React, { useState } from "react";
import { Box, TextField } from "@mui/material";
import Grid from "@mui/material/Grid2";

const AddQualificationForm = () => {
  const [qualification, setQualification] = useState({
    specialization: "",
    licenseNumber: "",
  });

  return (
    <Box sx={{ width: "100vw", padding: 2, border: "2px solid blue" }}>
      <Grid container spacing={2} sx={{ border: "2px dashed black", width: '100%' }}>
        {/* First Grid Item */}
        <Grid
          item
          xs={12}
          sm={6}
          sx={{
            border: "2px solid red", // Red border for the first item
          }}
        >
          <TextField label="First Name" fullWidth />
        </Grid>

        {/* Second Grid Item */}
        <Grid
          item
          xs={12}
          sm={6}
          sx={{
            border: "2px solid green", // Green border for the second item
          }}
        >
          <TextField label="Last Name" fullWidth />
        </Grid>
      </Grid>
    </Box>
  );
};

export default AddQualificationForm;

im want something like the attached picture:

picture

2

Answers


  1. Give parent grid width a 100% value

    Login or Signup to reply.
  2. You can make the grid items fill the available space with size="grow"

    <Grid container spacing={2}>
      {/* First Grid Item */}
      <Grid
        item
        size="grow"
      >
        <TextField label="First Name" fullWidth />
      </Grid>
    
      {/* Second Grid Item */}
      <Grid
        item
        size="grow"
      >
        <TextField label="Last Name" fullWidth />
      </Grid>
    </Grid>
    

    This, however, will not let you use the media breakpoints you specified. If you want to specify size based on those you would do something like this:

    <Grid container spacing={2}>
      {/* First Grid Item */}
      <Grid
        item
        size={{ xs: 12, sm: 6 }} 
      >
        <TextField label="First Name" fullWidth />
      </Grid>
    
      {/* Second Grid Item */}
      <Grid
        item
        size={{ xs: 12, sm: 6 }} 
      >
        <TextField label="Last Name" fullWidth />
      </Grid>
    </Grid>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search