add 'withRedirect' hoc
smeijer opened this issue · 2 comments
For adding redirect
actions to components, it's either necessary to pass through the router from parent to child, or get the router from context manually.
It would be nice if there was an withRedirect
hoc
exposed that takes redirectTo
from the context
, and merges it with the props
, so we could do something like:
export default compose(
withRedirect,
withHandlers(({ redirectTo }) => ({
onCancel: () => () => {
redirectTo('/');
},
onSubmit: () => async (data) => {
const id = await save(data);
redirectTo(`/blog/${id}`);
},
})),
)(Component)
I'm currently using recompose
for the job, but a withRedirect
would make it just a little prettier.
export defualt compose(
getContext({
redirectTo: () => null,
}),
withHandlers(({ redirectTo }) => ({
...
})),
)(Component);
Thanks for the suggestiing @smeijer. I'd like to explore this more. Can you share a bit more context? Is compose
a redux thing?
I've submitted a PR, I hope you'll find it useful.
The compose
thing is in my case from recompose
, but it's exported by a lot of libraries, and generally does the same thing everywhere. compose
isn't really necessary for the withRedirectTo
helper though, so I've removed it from the example in the PR #11.
compose
just "wraps" your Component
(or any other method) with a chain of methods. Instead of writing fn1(fn2(fn3()))
you can write compose(fn1, fn2)(fn3)
. Makes it a little more readable when the list gets long.