I’m going to explain how to create a very basic modal or dialog component in React JS and use it in other components in this post. Keep in mind that it is a very straightforward component without any particular designs. As a result, you can create your own designs. In addition, I employ the following tools and libraries:
- React JS
- tailwind
So let’s dive into the code. First, we develop the Dialog component in Dialog.tsx file.
import React, { useState } from 'react';
import styles from './Dialog.module.css';
import { Cross2Icon } from '@radix-ui/react-icons';
export default function Dialog({
display,
children,
title,
onClose,
}: {
display: boolean;
children: any;
title: string;
onClose: () => void;
}) {
const [startClose, setStartClose] = useState(false);
const onCloseClick = () =>{
setStartClose(true);
setTimeout(() => {setStartClose(false);onClose()}, 400)
}
return (
onCloseClick()}
>
{title}
{children}
);
}
Now we make a CSS file Dialog.module.css file in the component’s directory and develop codes to handle fade-in and fade-out animations for our Dialog display event.
.modal_fade_in {
-webkit-animation: modalFadeIn .4s; /* Safari, Chrome and Opera > 12.1 */
-moz-animation: modalFadeIn .4s; /* Firefox < 16 */
-ms-animation: modalFadeIn .4s; /* Internet Explorer */
-o-animation: modalFadeIn .4s; /* Opera < 12.1 */
animation: modalFadeIn .4s;
}
@keyframes modalFadeIn {
from {
scale: 0;
}
to {
scale: 1;
}
}
/* Firefox < 16 */
@-moz-keyframes modalFadeIn {
from {
scale: 0;
}
to {
scale: 1;
}
}
/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes modalFadeIn {
from {
scale: 0;
}
to {
scale: 1;
}
}
/* Internet Explorer */
@-ms-keyframes modalFadeIn {
from {
scale: 0;
}
to {
scale: 1;
}
}
/* Opera < 12.1 */
@-o-keyframes modalFadeIn {
from {
scale: 0;
}
to {
scale: 1;
}
}
.modal_fade_out {
-webkit-animation: modalFadeOut .4s; /* Safari, Chrome and Opera > 12.1 */
-moz-animation: modalFadeOut .4s; /* Firefox < 16 */
-ms-animation: modalFadeOut .4s; /* Internet Explorer */
-o-animation: modalFadeOut .4s; /* Opera < 12.1 */
animation: modalFadeOut .4s;
}
@keyframes modalFadeOut {
from {
scale: 1;
}
to {
scale: 0;
}
}
/* Firefox < 16 */
@-moz-keyframes modalFadeOut {
from {
scale: 1;
}
to {
scale: 0;
}
}
/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes modalFadeOut {
from {
scale: 1;
}
to {
scale: 0;
}
}
/* Internet Explorer */
@-ms-keyframes modalFadeOut {
from {
scale: 1;
}
to {
scale: 0;
}
}
/* Opera < 12.1 */
@-o-keyframes modalFadeOut {
from {
scale: 0;
}
to {
scale: 1;
}
}