hook-hoc
v1.2.0
Published
Use React hooks with your class components by Higher Order Component
Downloads
804
Maintainers
Readme
Hook Higher Order Component (HOC)
Use React hooks with your class components by Higher Order Component.
Warning:
This is intended to help incrementally transition large existing class components to hooks. Please write new components using functions!
Data fetching Example
Let's fetch some data using Reactive Data Client. We use the provided id
prop to know what to fetch, then inject user
and friends
by returning an object
with those props.
import withHook from 'hook-hoc';
import { useSuspense } from '@data-client/react';
import UserResource from 'resources/User';
const useProfile = ({ id }: { id: number }) => {
const user = useSuspense(UserResource.get, { id });
const friends = useSuspense(UserResource.getList, { id });
return { user, friends };
};
class Profile extends React.PureComponent<{
id: number;
user: UserResource;
friends: UserResource[];
}> {
//...
}
export default withHook(useProfile)(Profile);
Forms Example
Here's an example of using a theoretical forms handling library
import React from 'react';
import withHook from 'hook-hoc';
import { useFields, FormValues } from '@cb/forms';
import SignupForm from './SignupForm';
// export this for testing if needed
export function useSignupFields() {
const fields = useFields(SignupForm);
const [submit] = useSubmitter(SignupForm);
return { ...fields, submit };
}
type Props = FormValues<SignupForm> & {
submit: (options?: object) => Promise<any>;
};
class SignupFields extends React.PureComponent<Props> {
render() {
const { submit, username, password } = this.props;
return (
<form
onSubmit={e => {
e.preventDefault();
submit();
}}
>
<InputField {...username} />
<InputField {...password} type="password" />
<button type="submit">SignUp</button>
</form>
);
}
}
export default withHook(useSignupFields)(SignupFields);