Skip to content

Instantly share code, notes, and snippets.

@faceyspacey
Last active April 8, 2019 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save faceyspacey/42b89bd30f7309911ff66815f3adf382 to your computer and use it in GitHub Desktop.
Save faceyspacey/42b89bd30f7309911ff66815f3adf382 to your computer and use it in GitHub Desktop.
Respond Plus Hooks Modal
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>
)
}
@faceyspacey
Copy link
Author

faceyspacey commented Apr 8, 2019

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.

  • OUTSIDE: props.visible toggles visibility
  • INSIDE: close and submit can toggle visibility inside

There 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment