Search code examples
relayjs

Passing parameters from Relay router to component


In Relay, how do I pass a route parameter to the component?

I have this route:

import Relay from 'react-relay'

export default class ConversationRoute extends Relay.Route {
  static queries = {
    account: (Component) => Relay.QL`
      query root {
        account {
          ${Component.getFragment('account')}
        }
      }
    `
  }

  static paramDefinitions = {
    conversationId: {required: true}
  }

  static routeName = 'ConversationRoute'
}

And this component:

class CommentListApp extends React.Component {
  render() {
    let account = this.props.account
    if (!account) return <div />
    return <CommentList comments={account.conversation.comments} />
  }
}

export default Relay.createContainer(CommentListApp, {
  initialVariables: {
    conversationId: null
  },

  fragments: {
    account: () => Relay.QL`
      fragment on Account {
        conversation(id: $conversationId) @include(if: $conversationId) {
          comments {
            ${CommentList.getFragment('comments')}
          }
        }
      }
    `
  }
})

But that does not work. The conversationId parameter does not get passed into the component.

What am I missing?


Solution

  • Your queries should be:

    static queries = {
      account: (Component, params) => Relay.QL`
        query root {
          account {
            ${Component.getFragment('account', params)},
          },
        }
      `,
    }
    

    Note that you'd be just as well-served with the shorthand query syntax in your case, though.

    static queries = {
      account: () => Relay.QL`query { account }`,
    }