Declarative data dependencies

Relay uses the term colocation to describe declarative data dependencies that live beside the component that uses the data. This means that we don't have to go digging around for action creator functions that actually get the component data that is scattered across several modules. With colocation, we can see exactly what the component needs.

Let's get a taste of what this looks like. If you want to display the first and last name of a user, you need to tell Relay that your component needs this data. Then, you can rest assured that the data will always be there for your component. Here's an example:

const User = ({ first, last }) => ( 
  <section> 
    <p>{first}</p> 
    <p>{last}</p> 
  </section> 
); 
 
const UserContainer = Relay.createContainer(User, { 
  fragments: { 
    user: () => Relay.QL` 
      fragment on User { 
        first, 
        last, 
     } 
    `, 
  }, 
}); 

We have two components here. First, there's the User component. This is the application component that actually renders the UI elements for the first and last name data. Note that this is just a plain old React component, rendering props that are passed to it. As you can see with the UserContainer component that we've created, Relay follows the container pattern that you learned about earlier in this book. It's in the createContainer() function that we specify the data dependencies that this component needs by passing a fragment of GraphQL syntax.

Once again, don't dwell on the Relay/GraphQL specifics just yet. The idea here is to simply illustrate that this is all the code that we need to write to get our component the data it needs. The rest is just bootstrapping the Relay query mechanism, which you'll see in the next chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.47.253