Skip to content

Instantly share code, notes, and snippets.

@kdipaolo
Created May 28, 2018 14:33
Show Gist options
  • Save kdipaolo/74fd27c0e72c91abb37545e6ee40ddf0 to your computer and use it in GitHub Desktop.
Save kdipaolo/74fd27c0e72c91abb37545e6ee40ddf0 to your computer and use it in GitHub Desktop.
// Below I am using react's context api to create a modular way to manage modals within an application
// Context Environment
import React, { Component, createContext } from 'react'
const ModalContext = createContext({
component: null,
props: {},
showModal: () => {},
hideModal: () => {}
})
export class ModalProvider extends Component {
showModal = (component, props = {}) => {
this.setState({
component,
props
})
}
hideModal = () =>
this.setState({
component: null,
props: {}
})
state = {
component: null,
props: {},
showModal: this.showModal,
hideModal: this.hideModal
}
render() {
return (
<ModalContext.Provider value={this.state}>
{this.props.children}
</ModalContext.Provider>
)
}
}
export const ModalConsumer = ModalContext.Consumer
// Usage
import React from 'react'
import styled, { keyframes, css } from 'styled-components'
import { withRouter } from 'react-router-dom'
import { X } from 'react-feather'
import Modal from 'react-modal'
const XIcon = styled(X)`
overflow: hidden;
position: absolute;
right: -67px;
top: 9px;
background: gray;
padding: 3%;
border-radius: 50%;
color: #fff;
transition: 0.3s all ease;
&:hover {
transform: scale(1.2);
}
`
const fadeShow = keyframes`
0% {
opacity: 0;
transform: translate(-50%, -30%);
}
100% {
opacity: 1;
transform: translate(-50%, -55%);
}
`
const ModalWrapper = styled(Modal)`
animation: ${fadeShow} 0.3s ease-out forwards;
max-width: 500px;
width: 50%;
padding: 3%;
height: auto;
z-index: 999999999999999;
position: fixed;
border-radius: 6px;
top: 50%;
left: 50%;
box-shadow: 0 8px 15px 0 rgba(68, 80, 82, 0.06);
background: #fff;
${props =>
props.width &&
css`
width: ${props => props.width}px;
`};
@media (max-width: 400px) {
width: 90%;
}
`
const Close = styled.button``
const ModalBox = props => {
return (
<ModalWrapper onRequestClose={props.onRequestClose} isOpen>
<Close href="" onClick={props.onRequestClose}>
<XIcon />
</Close>
{props.children}
</ModalWrapper>
)
}
export default ModalBox
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment