Skip to content

Instantly share code, notes, and snippets.

@jwietelmann
Created October 20, 2016 16:00
Show Gist options
  • Save jwietelmann/456504bf51d24f2a93a25d57f9bfb250 to your computer and use it in GitHub Desktop.
Save jwietelmann/456504bf51d24f2a93a25d57f9bfb250 to your computer and use it in GitHub Desktop.
A dumb thing I hacked up without testing. For helping make stupid modals in React.
import React, {Component, Children} from 'react'
import {connect} from 'react-redux'
const MODAL_CHANGE = 'MODAL_CHANGE'
// Maintain a single active modal identifier
export function modalReducer(state = {activeModalId: null}, {type, id}) {
if(type !== MODAL_CHANGE) {
return state
}
const {activeModalId} = state
if(activeModalId === id) {
return state
}
return {...state, activeModalId: id}
}
// Sets the activeModalId
export function createOpenModalAction(id) {
return {type: MODAL_CHANGE, id}
}
// Nulls out the activeModalId
export function createCloseModalAction() {
return openModal(null)
}
// Only displays children when modalId === activeModalId
class DumbModalDisplay extends Component {
static propTypes = {
modalId: PropTypes.any.isRequired,
activeModalId: PropTypes.any,
children: PropTypes.element,
}
render() {
if(!this.props.children) {
return null
}
if(this.props.modalId !== this.props.activeModalId) {
return null
}
return Children.only(this.props.children)
}
}
// The redux-connected version we'll actually use
export const ModalDisplay = connect(
({activeModalId}) => ({activeModalId})
)(DumbModalDisplay)
// Use this to create buttons and other things that open/close modals
export function connectModalActions(component) {
return connect(null, {
openModal: createOpenModalAction,
closeModal: createCloseModalAction,
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment