withProps
withProps is a higher-order component (HOC) that connects a React component to the Redux store. It uses react-redux’s connect function along with selectors and optional action creators to provide state and dispatch props to the component.
Importing
To use withProps, import it from @blue-functor/remodel:
import { withProps } from '@blue-functor/remodel';Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
selectors | Record<string, any> or StructuredSelectorCreator | Yes | A map of state keys to selector functions, or a structured selector function, to derive state props. |
actionCreators | Record<string, any> | No | A map of action creators to be bound and provided as dispatch props. |
mergeProps | (stateProps, dispatchProps, ownProps) => any | No | Custom function to merge state, dispatch, and own props into the final props passed to the component. |
options | Record<string, any> | No | Additional options for react-redux’s connect function. |
Returns
An enhanced component with the selected state and dispatch props injected.
Example Usage
src/components/UserComponent.tsx
import React from 'react';
import { withProps } from '@blue-functor/remodel';
import { userDetails, signIn } from '@/models/users';
type Props = {
userDetails: ReturnType<typeof userDetails>;
signIn: typeof signIn;
};
const UserComponent: React.FC<Props> = ({ userDetails, signIn }) => (
<div>
<h1>User: {userDetails.username}</h1>
<button onClick={() => signIn({ username: 'test', password: 'password' })}>
Sign In
</button>
</div>
);
export default withProps({ userDetails }, { signIn })(UserComponent);In this example:
selectorsmaps the Redux state to theuserprop using theuserDetailsselector.actionCreatorsmaps thesignInaction creator to thesignInprop, allowing it to be called directly from the component.
How It Works
-
Selectors:
- If
selectorsis a structured selector, it combines individual selectors into a single selector function. - If
selectorsis a custom function, it is used directly to derive the state props.
- If
-
Action Creators:
- Action creators are bound to the Redux
dispatchfunction, providing dispatch props to the component.
- Action creators are bound to the Redux
-
Merge Props:
- If
mergePropsis provided, it customizes how the state, dispatch, and own props are combined before being passed to the component.
- If
-
Options:
- Additional options can be passed to
react-redux’sconnectfunction for advanced configurations.
- Additional options can be passed to
withProps simplifies the connection between your Redux store and React components, reducing boilerplate and ensuring type safety with structured selectors and action creators.