Jason Jason - 1 year ago 235
React JSX Question

How do you get URL parameters from react-router outside components to use in GraphQL query

Is it possible to access the URL params supplied in a route outside the components?

This of course can be accomplished with

but I am looking for something in the react-router API to do this more cleanly.

Additionally, if there is a more standard approach to doing this with GraphQL, that's even better! I am just looking into browser clients for gql and new to gql in general.

Example component:

import React from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import get from 'lodash.get';

const ContractComponent = (props) => {

const ContractQuery = gql`query ContractQuery ($contractId: String!){
contract(id: $contractId) {

const ContractWithData = graphql(ContractQuery, {
options: { variables: { contractId: contractId } }, // <-- var i want to pull from url params

export default ContractWithData;

Example route:

<Route path="contract/:contractId" component={Contract} />

Answer Source

I'm not really familiar with react-apollo, but I think the following is a good of achieving what you want. You can see in the docs that options can be a function taking the component props as input, returning an object with the options: http://dev.apollodata.com/react/queries.html#graphql-options

So I think you can do:

const ContractWithData = graphql(ContractQuery, {
    options: props => ({ variables: { contractId: props.params.contractId } })

In the code above, props.params are the params passed by react-router to the route component (nothing special there).

You want to write options as a function when you need do to something dynamic at runtime, in this case accessing the route params.

Hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download