Coder Social home page Coder Social logo

react-router-relay's Introduction

react-router-relay Travis npm

Relay integration for React Router.

Discord

Usage

Use <RelayRouter> or <RelayRouterContext> instead of <Router> or <RouterContext> respectively, then define Relay queries and render callbacks for each of your routes:

import { RelayRouter } from 'react-router-relay';

/* ... */

const ViewerQueries = {
  viewer: () => Relay.QL`query { viewer }`
};

const WidgetQueries = {
  widget: () => Relay.QL`query { widget(widgetId: $widgetId) }`
}

ReactDOM.render((
  <RelayRouter history={history}>
    <Route
      path="/" component={Application}
      queries={ViewerQueries}
    >
      <Route
        path="widgets" component={WidgetList}
        queries={ViewerQueries}
        queryParams={['color']} stateParams={['limit']}
        prepareParams={prepareWidgetListParams}
        renderLoading={() => <Loading />}
      />
      <Route
        path="widgets/:widgetId" component={Widget}
        queries={WidgetQueries}
      />
    </Route>
  </RelayRouter>
), container);

react-router-relay will automatically generate a combined Relay route with all queries and parameters from the active React Router routes, then pass down the query results to each of the route components. As the queries are all gathered onto a single route, they'll all be fetched at the same time, and the data for your entire page will load and then render in one go.

You can find an example implementation of TodoMVC with routing using react-router-relay at https://github.com/taion/relay-todomvc.

Guide

Installation

Note: Releases from v0.9.0 onward only support React Router v2.x. For React Router 1.x support, use v0.8.0 or earlier.

$ npm install react react-dom react-relay react-router
$ npm install react-router-relay

Routes and queries

For each of your routes that requires data from Relay, define a queries prop on the <Route>. These should be just like the queries on a Relay route:

const ViewerQueries = {
  viewer: () => Relay.QL`query { viewer }`
};

const applicationRoute = (
  <Route
    path="/" component={Application}
    queries={ViewerQueries}
  />
);

Just like with Relay.RootContainer, the component will receive the query results as props, in addition to the other injected props from React Router.

If your route doesn't have any dependencies on Relay data, just don't declare queries. The only requirement is that any route that does define queries must have a Relay container as its component.

Any URL parameters for routes with queries and their ancestors will be used as parameters on the Relay route:

const WidgetQueries = {
  widget: () => Relay.QL`
    query {
      widget(widgetId: $widgetId) # `widgetId` receives a value from the route
    }
  `
}

class Widget extends React.Component { /* ... */ }

Widget = Relay.createContainer(Widget, {
  fragments: {
    widget: () => Relay.QL`
      fragment on Widget {
        name
      }
    `
  }
});

// This handles e.g. /widgets/3.
const widgetRoute = (
  <Route
    path="widgets/:widgetId" component={Widget}
    queries={WidgetQueries}
  />
);

If your route requires parameters from the location query or state, you can specify them respectively on the queryParams or stateParams props on the <Route>. URL and query parameters will be strings, while missing query and state parameters will be null.

If you need to convert or initialize these parameters, you can do so with prepareParams, which has the same signature and behavior as prepareVariables on a Relay container, except that it also receives the React Router route object as an argument.

Additionally, you can use route parameters as variables on your containers:

class WidgetList extends React.Component { /* ... */ }

WidgetList = Relay.createContainer(WidgetList, {
  initialVariables: {
    color: null,
    size: null,
    limit: null
  },

  fragments: {
    viewer: () => Relay.QL`
      fragment on User {
        widgets(color: $color, size: $size, first: $limit) {
          edges {
            node {
              name
            }
          }
        }
      }
    `
  }
});

function prepareWidgetListParams(params, route) {
  return {
    ...params,
    size: params.size ? parseInt(params.size, 10) : null,
    limit: params.limit || route.defaultLimit
  };
};

// This handles e.g. /widgets?color=blue&size=3.
const widgetListRoute = (
  <Route
    path="widgets" component={WidgetList}
    queries={ViewerQueries}
    queryParams={['color', 'size']} stateParams={['limit']}
    prepareParams={prepareWidgetListParams}
    defaultLimit={10}
  />
);

Render callbacks

You can pass in custom renderLoading, renderFetched, and renderFailure callbacks to your routes:

<Route /* ... */ renderLoading={() => <Loading />} />

These have the same signature and behavior as they do on Relay.RootContainer, except that the argument to renderFetched also includes the injected props from React Router. As on Relay.RootContainer, the renderLoading callback can simulate the default behavior of rendering the previous view by returning undefined.

Additional Relay.RootContainer configuration

We pass through additional props on <RelayRouter> or <RelayRouterContext> are to the underlying Relay.RootContainer. You can use this to control props like forceFetch on the Relay.RootContainer:

<RelayRouter
  history={history} routes={routes}
  forceFetch={true}
/>

Notes

  • react-router-relay currently does not support named components.
  • react-router-relay only updates the Relay route on actual location changes. Specifically, it will not update the Relay route after changes to location state, so ensure that you update your container variables appropriately when updating location state.
  • react-router-relay uses referential equality on route objects to generate unique names for queries. If your route objects do not maintain referential equality, then you can specify a globally unique name property on the route to identify it.
  • Relay's re-rendering optimizations only work when all non-Relay props are scalar. As the props injected by React Router are objects, they disable these re-rendering optimizations. To take maximum advantage of these optimizations, you should make the render methods on your route components as lightweight as possible, and do as much rendering work as possible in child components that only receive scalar and Relay props.

Authors

react-router-relay's People

Contributors

chentsulin avatar colllin avatar cpojer avatar devknoll avatar josephsavona avatar sgwilym avatar simondegraeve avatar taion avatar

Watchers

 avatar  avatar  avatar

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.