Last active
April 8, 2019 14:03
-
-
Save faceyspacey/42b89bd30f7309911ff66815f3adf382 to your computer and use it in GitHub Desktop.
Respond Plus Hooks Modal
This file contains 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
const MyRespondModal = (props, state, actions) => ( | |
<Modal | |
visible={!!state.modalText} | |
text={state.modalText} | |
onClose={actions.cancel} | |
onSubmit={actions.confirm} | |
/> | |
) | |
const Modal = ({ visible, text, onClose, onSubmit }) => { | |
const [show, setVisible] = useState(visible) | |
useEffect(() => setVisible(visible), [visible]) | |
console.log('render', show) // this will render 2x instead of 1x | |
if (!show) return null | |
const close = () => { | |
setVisible(false) | |
onClose && onClose() | |
} | |
const submit = () => { | |
setVisible(false) | |
onSubmit && onSubmit() | |
} | |
return ( | |
<div> | |
<span onClick={close}>x</span> | |
<h1>{text}</h1> | |
<button onClick={submit}>SUBMIT</button> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Basically, this can be achieved with
getDerivedStateFromProps
in a class component, but not with hooks.What's really going on? What's the real goal?
The real goal is a component that is both managed and unmanaged. Both controlled from the outside and the inside.
props.visible
toggles visibilityclose
andsubmit
can toggle visibility insideThere are ways to make it work, i.e. we could pass the parent's
setVisible
handler to the child (and therefore only the parent sets visibility), but this defeats the purpose. The purpose is so Redux can "drive" a modal component like this with a simple boolean value.