Use styled-components to center React Bootstrap Modal

Viewed 675

Is it possible to use styled-component to create a wrapper container containing React Bootstrap's Modal component in order to make the modal be both horizontally and vertically aligned?

Tried creating CenteredModal container as shown, but the .modal element does not appear to have the new styles applied to it.

import { Modal } from "react-bootstrap";
import styled from 'styled-components';

const CenteredModal = styled.div`
    & .modal {
        display: flex !important;
        align-items: center;
    }
`

interface MyModalProps {
    isOpen: boolean,
    onHide: () => void
}

export default function MyModal({
    isOpen = false,
    onHide,
}: MyModalProps) {
    return (
        <CenteredModal>
            <Modal show={isOpen} onHide={onHide}>
                <h1>Hello</h1>
            </Modal>
        </CenteredModal>
    )
} 
4 Answers

Because Modal of react-bootstrap isn't render inside CenteredModal, so your style can't affect it (You can open the browser developer tool to see, it should be rendered at the bottom of the html body not in the CenteredModal div element).

I saw react-bootstrap is already provides a centering method, is this what you want? you can take a look https://react-bootstrap.github.io/components/modal/

why not use centered prop ? example :

<Modal
  size="lg"
  centered
>

Your new container just needs a little tweaking:

const CenteredModal = styled.div`
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
`

You can use this syntax:

import { Modal } from "react-bootstrap";
import styled from 'styled-components';

const CenteredModal = styled(Modal)`
    display: flex !important;
    align-items: center;
`;
Related