Skip to main content
🍞
Dev Corner
How to Pass a GraphQL Response as Props to a React Component?

How to Pass a GraphQL Response as Props to a React Component?

The Crystallize React frontend boilerplate folder ships with a couple of nifty functions that will help you become a developer rockstar in no time. They are basic building blocks that make your components come alive with product data delivered super fast from Crystallize.

Crystallize delivers product information data using GraphQL. The boilerplate uses an export in the graph-data.js files to define how your data should be presented in your component.

Passing the GraphQL props

In our components you will see that whenever we query Crystallize for product data, we export our component like this:

export default withData(graphql(query)(MyComponent));

The withData function is one of those awesome functions that I would have loved to have when I first started out. It magically ties your GraphQL query up with your component and initiates the Apollo client. By doing so you can both access your GraphQL response, router, and provider states in your component like so:

class CategoryPage extends React.PureComponent {
  render() {
    const { data } = this.props;

    if (data.loading) {
      return 'Loading...';
    }

    if (data.error) {
      return 'Something went wrong...';
    }

    return (
      <div>
        <h1>Category page</h1>
        <ul>
          {data.catalogue.children.map(p => (
            <div key={p.id}>{p.name}</div>
          ))}
        </ul>
      </div>
    );
  }
}

That’s it. Your component is now fully populated with product data and you can present it however you like.