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

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

Passing a GraphQL response as props to a React component involves several steps that ensure the data fetched from a GraphQL server is effectively used within your React application.

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. These basic building blocks 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 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; you can present it however you like.

Remember, the actual implementation details may vary based on your specific requirements, the complexity of your product data, and the structure of your application.

Need further assistance? Ask the Crystallize team or other enthusiasts in our Slack community.