Sometimes, we want to add a close icon in React Material UI Dialog header’s top right corner.
In this article, we’ll look at how to add a close icon in React Material UI Dialog header’s top right corner.
How to add a close icon in React Material UI Dialog header’s top right corner?
To add a close icon in React Material UI Dialog header’s top right corner, we can put the title and the close icon in a Grid
component.
For instance, we write:
import * as React from "react";
import Dialog from "@material-ui/core/Dialog";
import DialogTitle from "@material-ui/core/DialogTitle";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import IconButton from "@material-ui/core/IconButton";
import CloseIcon from "@material-ui/icons/Close";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid";
export default function App() {
const [open, setOpen] = React.useState();
return (
<div>
<Button onClick={() => setOpen(true)}>Open</Button>
<Dialog open={open} onClose={() => setOpen(false)}>
<DialogTitle>
<Grid container justify="space-between" alignItems="center">
<Typography variant="div">Dialog</Typography>
<IconButton onClick={() => setOpen(false)}>
<CloseIcon />
</IconButton>
</Grid>
</DialogTitle>
<DialogContent>
<DialogContentText>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla massa
felis, dapibus eget posuere ut, lobortis id purus.
</DialogContentText>
</DialogContent>
</Dialog>
</div>
);
}
To add the dialog box, we add the Dialog
component. We also have a Open Button
to open the dialog when we click it.
We set the open
state with setOpen
to true
so that we open the dialog.
And we set the open
prop of Dialog
to the open
state to use the open
state to control when the Dialog
is opened.
We add the DialogTitle
component to add the dialog title. And we add the Grid
component inside it to add a flex container that we use to layout the title and close button.
We set the container
prop to true
to add make the Grid
a flex container.
And then we set justify
to 'space-between'
and alignItems
to 'center'
to put the title on the top left corner and the close button on the top right corner.
We set the onClick
prop of the IconButton
to a function that calls setOpen
to false
to close the dialog.
Also, we set the onClose
prop to the same function to close it when we click outside the dialog box.
We add the dialog content in the DialogContentText
component.
Conclusion
To add a close icon in React Material UI Dialog header’s top right corner, we can put the title and the close icon in a Grid
component.