Last active
November 24, 2016 16:19
-
-
Save jazlalli/dffc0141964c60ea0d25a81e3da7c3e5 to your computer and use it in GitHub Desktop.
A higher-order React component for wrapping things in a Modal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component, PropTypes } from 'react'; | |
import Modal from 'react-modal'; | |
/* | |
@desc: wraps any component provided in a react-modal | |
@param: ModalContent - any React component that you want as a modal | |
@param: Trigger (optional) - a clickable component that will trigger the modal to open | |
@param: triggerProps (optional) - some data to provide to the trigger component | |
@usage: | |
const SignUpLink = () => <a>Sign Up</a> | |
const MyForm = () => ( | |
<form | |
onSubmit={(e) => { | |
// do stuff... | |
this.props.closeModal(e, formData) <-- send data up | |
}} | |
> | |
{ // form content } | |
</form> | |
); | |
const SignUpModal = modalify(MyForm, SignUpLink); | |
// now render SignUpModal somewhere... | |
render() { | |
return ( | |
<SignUpModal | |
onModalClose={(evt, data) => { | |
console.log(data); <-- receive the data passed by the form! | |
}} | |
/> | |
); | |
} | |
*/ | |
const modalify = (ModalContent, Trigger, triggerProps) => { | |
class ModalWrapper extends Component { | |
constructor(props) { | |
super(props); | |
this.openModal = this.openModal.bind(this); | |
this.closeModal = this.closeModal.bind(this); | |
this.state = { | |
isOpen: false, | |
} | |
} | |
openModal(evt) { | |
this.setState({ | |
isOpen: true, | |
}); | |
} | |
closeModal(evt, data) { | |
this.setState({ | |
isOpen: false, | |
}, () => this.props.onModalClose(evt, data)); // pass data from the modal up | |
} | |
render() { | |
const triggerProps = triggerProps || {}; | |
const trigger = Trigger | |
? <Trigger onClick={this.openModal} {...triggerProps} /> | |
: null; | |
return ( | |
<div> | |
{ trigger } | |
<Modal | |
overlayClassName="modal-overlay" | |
className="modal modal-container" | |
isOpen={this.state.isOpen} | |
onRequestClose={this.closeModal} | |
> | |
<ModalContent closeModal={this.closeModal} {...this.props} /> | |
</Modal> | |
</div> | |
); | |
} | |
} | |
ModalWrapper.propTypes = { | |
onModalClose: PropTypes.func, | |
}; | |
return ModalWrapper; | |
}; | |
export default modalify; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment