GithubHelp home page GithubHelp logo

connectWithRouter about react HOT 10 CLOSED

ui-router avatar ui-router commented on April 25, 2024
connectWithRouter

from react.

Comments (10)

elboman avatar elboman commented on April 25, 2024 3

Yeah, I was thinking that with the new context API we should get the connectWithRouter functionality for free, by simply consuming the context that will provide the router instance.

from react.

nateabele avatar nateabele commented on April 25, 2024 1

@schlesiger You may want to fix your readme. It says npm install react-swipeable-views.

from react.

wallzero avatar wallzero commented on April 25, 2024 1

Whoops that's embarrassing. I'll update it along with these changes. Thanks!

from react.

elboman avatar elboman commented on April 25, 2024

Why do you feel you would need to access the context? Do you need the router instance?

Because you can always bootstrap the router manually and pass the instance to the UIRouter component. You can also access the router via the transition object that is injected via prop by the UIView component.

from react.

wallzero avatar wallzero commented on April 25, 2024

I can use the instance passed from UIView, but that becomes inconvenient if the component which requires router is deeply nested. Also, whether I bootstrap the router myself or not, the instance is still passed in context and I can use the above ConnectWithRouter.

The above HOC is really to act somewhat like dependency injection. My components can remain unaware of UIRouter and are simply passed predefined functions which are responsible for interacting with the router instance. It's the same pattern as react-redux's connect.

Including ConnectWithRouter or something similar is simply a convenience for users. They can always write it themselves.

from react.

nateabele avatar nateabele commented on April 25, 2024

I think I understand what you're saying. Maybe a better question is: is there something specific you need to access the router instance for that isn't provided by the existing state/view management APIs? Thanks.

from react.

mhemrg avatar mhemrg commented on April 25, 2024

I think it is necessary, too. I implemented it in my project but it's better to find it in the main package.

from react.

nateabele avatar nateabele commented on April 25, 2024

Okay, can you guys please explain some use cases so we can understand how best to approach the problem? Thanks.

from react.

mhemrg avatar mhemrg commented on April 25, 2024

So let's imagine that you have some nested components and your root component is connected to router via UIView and it has access to transition object. But how about the child components? You have to pass the object through your components and it is inconvenient.

from react.

wallzero avatar wallzero commented on April 25, 2024

Several months later and I think I am becoming proficient with TypeScript. :-)

I have an updated connectWithRouter HOC written in TypeScript:

import {UIRouterReact} from '@uirouter/react';
import PropTypes from 'prop-types';
import React, {
  Component,
  ComponentType
} from 'react';

// Diff / Omit taken from:
// https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-311923766
// Native `Exclude` can replace `Diff` in `typescript@^2.8.0`
export type Diff<T extends string, U extends string> =
  ({ [P in T]: P } & { [P in U]: never } & { [x: string]: never })[T];
export type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>;

export const defaultUpdate = (router: UIRouterReact, forceUpdate: () => void) => (
  router.transitionService.onSuccess({},() => (forceUpdate()))
);

export default <TRouterProps, TNeedsProps extends {}>(
  params: (
    router?: UIRouterReact,
    ownProps?: TNeedsProps
  ) => TRouterProps = (
    router: UIRouterReact,
    ownProps
  ) => ({
    ...ownProps as {},
    router
  } as any),
  update: false | typeof defaultUpdate = defaultUpdate
) => (
  <P extends TRouterProps, C extends {router: UIRouterReact}>(
    WrappedComponent: ComponentType<P>
  ) => (
    class Connector extends Component<
      Omit<P, keyof TRouterProps> & TNeedsProps,
      Omit<P, keyof TRouterProps> & TNeedsProps
    > {
      public static contextTypes = {
        router: PropTypes.object
      };

      public constructor(props: P & TNeedsProps, context: C) {
        super(props, context);
        this.context = context;

        this.state = params(this.context.router, this.props as any) as any;

        if (update) {
          update(this.context.router, () => {
            this.setState(params(this.context.router, this.props as any));
            return this.forceUpdate();
          });
        }
      }

      public render() {
        return (
          <WrappedComponent
            {...this.state}
            {...this.props}
          />
        );
      }
    }
  )
);

In addition to the params function accepting router, it now also accepts ownProps similar to react-redux in order to allow returning router props that change depending on the props initially passed.

Also, I ran into an issue where I would need the component to receive the latest values from the router, but a shallow compare of render doesn't trigger an update. To resolve this I added a second optional update function. It defaults to triggering a forceUpdate() on every state transition but can be updated with a more finely tuned function or disabled.

Soon I will be exporting connectWithRouter in ui-router-react-digest. I could open a PR if interested, but with react@^16.3.0 and the new context API, this may be obsolete in the future in favor of a simpler component. I will try out the new context API once the react type definitions are updated.

EDIT: HOC now caches props in state for more fine tuned control of updates.

from react.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.