Search code examples
javascriptgraphqlrelayjsrelay

Relay: use constant inside Fragment instead of graphql`...`


Relay createFragmentContainer is useful feature and it is easy to use:

const MyComponent = createFragmentContainer(
    MyFragmentComponent,
    {
        job: graphql`
            fragment MyComponent_job on Job {
                id
            }
        `
    }
);

The problem is it really hard to read code when query is at the end of my file. I prefer to have it at the top right after imports. Like this:

const QUERY_FRAGMENT = graphql`
    fragment MyComponent_job on Job {
        id
    }     
`
// Main code here

const MyComponent = createFragmentContainer(
    MyFragmentComponent,
    {
        job: QUERY_FRAGMENT
    }
);

But relay compiler throws error in that case: FindGraphQLTags: 'createFragmentContainer' expects fragment definitions to be 'key: graphql'.

Is there a way to separate createFragmentContainer and graphql?


Solution

  • This seems to be a known issue with babel-plugin-relay. As noted in this issue, the workaround is to change your imports:

    import Relay, { graphql } from 'react-relay'
    
    const fragment = graphql`...`
    
    ...
    
    Relay.createFragmentContainer(Component, fragment)