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

ParameterTypeRequiredDescription
selectorsRecord<string, any> or StructuredSelectorCreatorYesA map of state keys to selector functions, or a structured selector function, to derive state props.
actionCreatorsRecord<string, any>NoA map of action creators to be bound and provided as dispatch props.
mergeProps(stateProps, dispatchProps, ownProps) => anyNoCustom function to merge state, dispatch, and own props into the final props passed to the component.
optionsRecord<string, any>NoAdditional 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:

  • selectors maps the Redux state to the user prop using the userDetails selector.
  • actionCreators maps the signIn action creator to the signIn prop, allowing it to be called directly from the component.

How It Works

  1. Selectors:

    • If selectors is a structured selector, it combines individual selectors into a single selector function.
    • If selectors is a custom function, it is used directly to derive the state props.
  2. Action Creators:

    • Action creators are bound to the Redux dispatch function, providing dispatch props to the component.
  3. Merge Props:

    • If mergeProps is provided, it customizes how the state, dispatch, and own props are combined before being passed to the component.
  4. Options:

    • Additional options can be passed to react-redux’s connect function for advanced configurations.

withProps simplifies the connection between your Redux store and React components, reducing boilerplate and ensuring type safety with structured selectors and action creators.