Simple modal component using styled components

Styled component is a react library that enables developers to write integrated programmable styles within their react components.

styled component modal demo screenshot

We start with a react starter app and install styled-components

yarn add styled-components

Then create a functional component and import styled-components and define all the layers of a Modal component and style of them.

import React, { Fragment } from "react";
import {
 ModalBlock,
 ModalBody,
 ModalClose,
 ModalContainer,
 ModalFooter,
 ModalHeader,
 ModalOverlay,
 ModalTitle,
} from "./modal.styles";

const Modal = ({ title, footer, children, active, hideModal }) => {
 return (
 <Fragment>
 {active && (
 <ModalBlock>
 <ModalOverlay onClick={() => hideModal()}></ModalOverlay>
 <ModalContainer>
 <ModalHeader>
 <ModalTitle>{title}</ModalTitle>
 <ModalClose onClick={() => hideModal()}>X</ModalClose>
 </ModalHeader>
 <ModalBody>{children}</ModalBody>
 <ModalFooter>{footer}</ModalFooter>
 </ModalContainer>
 </ModalBlock>
 )}
 </Fragment>
 );
};
export default Modal;

A div block to position its children in the centre of the page. An overlay to distinguish the modal component over the page and a close button on the component, both of which are used to close the modal.

import React, { Fragment } from "react";
import {
 ModalBlock,
 ModalBody,
 ModalClose,
 ModalContainer,
 ModalFooter,
 ModalHeader,
 ModalOverlay,
 ModalTitle,
} from "./modal.styles";

const Modal = ({ title, footer, children, active, hideModal }) => {
 return (
 <Fragment>
 {active && (
 <ModalBlock>
 <ModalOverlay onClick={() => hideModal()}></ModalOverlay>
 <ModalContainer>
 <ModalHeader>
 <ModalTitle>{title}</ModalTitle>
 <ModalClose onClick={() => hideModal()}>X</ModalClose>
 </ModalHeader>
 <ModalBody>{children}</ModalBody>
 <ModalFooter>{footer}</ModalFooter>
 </ModalContainer>
 </ModalBlock>
 )}
 </Fragment>
 );
};
export default Modal;

To use the component in a page, define a state and toggle function to switch the state, then just import the modal and assign the state and toggle function along with other properties.

const App = () => {
 const [active, setActive] = useState(false);
 return (
 <div>
 <Button onClick={() => setActive(true)}>Open Modal</Button>
 <Modal
 active={active}
 hideModal={() => setActive(false)}
 title="Modal title goes here"
 footer={<Button>Footer Button</Button>}
 >
 Modal body content goes here..
 </Modal>
 </div>
 );
};

Styled-components are not as difficult as I thought, it is a delight to work with. It is faster and makes code more modular and maintainable.

Source code :

https://github.com/gladius/Simple-Styled-Component-Modal