NickCis / react-data-ssr

Data fetching for React components (Client & SSR)
MIT License
13 stars 0 forks source link

Add a default `mapArgsToProps` for `react-router-config` #2

Open NickCis opened 6 years ago

NickCis commented 6 years ago
const mapArgsToProps = (branch, extra) => {
  let { match } = branch || {};

  // On SSR params have to be fixed: https://github.com/ReactTraining/react-router/issues/5296
  if (match && match.params) {
    match = {
      ...branch.match,
      params: Object.keys(branch.match.params).reduce((acc, k) => {
        acc[decodeURIComponent(k)] = decodeURIComponent(branch.match.params[k]);
        return acc;
      }, {}),
    };
  }

  return {
    match,
  };
};

export default mapArgsToProps;
NickCis commented 6 years ago

In addition:

import React from 'react';
import PropTypes from 'prop-types';
import hoistNonReactStatics from 'hoist-non-react-statics';

const withRouterFix = Component => {
  if (typeof window !== 'undefined') return Component;

  const HOC = ({ match, ...props }) => {
    // On SSR params have to be fixed: https://github.com/ReactTraining/react-router/issues/5296
    if (match && match.params) {
      match = {
        ...match,
        params: Object.keys(match.params).reduce((acc, k) => {
          acc[decodeURIComponent(k)] = decodeURIComponent(match.params[k]);
          return acc;
        }, {}),
      };
    }

    return <Component {...props} match={match} />;
  };

  HOC.displayName = `withRouterFix(${Component.displayName || Component.name})`;
  HOC.propTypes = {
    match: PropTypes.object,
  };

  return hoistNonReactStatics(HOC, Component);
};

export default withRouterFix;