I am building a form using MUI. I have 6 fields and want to place them 3 of them on the left and the rest on the right, with a minimal gap. This is what I want to achieve:
This is what I have currently:
So far I have tried the gap property but no luck. I might be using the flex incorretly but again I’m not sure. This is the code I have:
import styled from "@emotion/styled";
import {
Box,
Button,
Container,
CssBaseline,
Grid,
Link,
TextField,
Typography,
} from "@mui/material";
import React, { useState } from "react";
const Field = styled(TextField)`
// Custom TextField to avoid styling repetitions
width: 650px;
`;
const FieldName = styled(Typography)`
// Custom Typography to avoid styling repetitions
font-weight: 700;
`;
const asterisk = <span style={{ color: "red" }}>*</span>;
const MailThread = () => {
const [formData, setFormData] = useState({
threadName: "",
from: "Qmeter or 2354",
customerName: "",
subject: "",
dropdownOption: "QNP-102 Template",
to: [],
startSending: new Date(),
});
const {
threadName,
from,
customerName,
subject,
dropdownOption,
to,
starSending,
} = formData;
const onChange = (e) => {
setFormData((prevState) => ({
...prevState,
[e.target.name]: e.target.value,
}));
};
const onSubmit = (e) => {
e.preventDefault();
};
return (
<Container maxWidth={false} component="main">
<CssBaseline />
<Box component="form" noValidate onSubmit={onSubmit} sx={{ mt: 3, display:'flex' }}>
<Grid container spacing={2}>
<Grid item xs={12}>
<FieldName>Thread Name{asterisk}</FieldName>
<Field
name="threadName"
required
value={threadName}
onChange={onChange}
/>
</Grid>
<Grid item xs={12}>
<FieldName>From</FieldName>
<Field
sx={{
backgroundColor: "#f8f4f4",
}}
disabled
value={from}
name="from"
onChange={onChange}
/>
</Grid>
<Grid item xs={12}>
<FieldName>If Customer name is empty</FieldName>
<Field onChange={onChange} />
</Grid>
<Grid item xs={12}>
<FieldName>Subject</FieldName>
<Field placeholder="Enter subject here" onChange={onChange} />
</Grid>
<Grid item xs={12}></Grid>
</Grid>
<Grid container spacing={2} sx={{marginLeft:'10px'}}>
<Grid item xs={12}>
<FieldName>Template</FieldName>
<Field placeholder="Enter subject here" onChange={onChange} />
</Grid>
</Grid>
</Box>
</Container>
);
};
export default MailThread;
3
Answers
The only thing you need to use
gap
property is displaygrid
orflex
.After you can apply
gap
in proper units:px
,%
,vw
,vh
…You can also use
margin-right
(apply on the left block).I personally don’t like the idea of setting container and spacing in the Grid component because it adjusts the layout with margins.
Please check the following code, which sets up a layout using flex and grap.
If you don’t want to use the properties of the Gird component, you may replace it with the Box component.
Good luck!
I just updated your code. here you can see the live example
please also read this documentation Grid