React.js & GraphQL

Bart Jeukendrup

bart@infty.io

@bartjkdp

  • PHP
  • Python
  • Javascript (jQuery)
  • MySQL
  • Memcached
  • Elasticsearch
  • RabbitMQ

React

A JavaScript library for building user interfaces

MVC, MVVM

Model

View

Two-way binding

State

View

Dispatcher

Action

view = f(state)

{
    questions: [
        {
            guid: 47564332,
            title: "FOR doorschuiven naar een andere VOF?",
            owner: {
                username: "rdamstra",
                name: "Frekie"
            }
        },
        ....
    ]
}
"use strict";

ReactDOM.render(React.createElement(
  "div",
  null,
  React.createElement(
    "h1",
    null,
    "Hello, world!"
  ),
  React.createElement(
    "p",
    { "class": "fun" },
    "It's lovely in here."
  )
), document.getElementById("root"));

ES5

ReactDOM.render(
  <div>
    <h1>Hello, world!</h1>
    <p class="fun">
        It's lovely in here.
    </p>
  </div>,
  document.getElementById("root")
);

JSX

  • Is declarative
  • Has unidirectional data flow
  • Allows to create reusable components
  • Allows server-side rendering

So React...

GraphQL

A query language for your API

Traditional REST

GraphQL

{
    questions(first: 10) {
        title
        owner {
            name
        }
        comments(first: 5) {
            description
        }   
    }
}
/api/v1/me
/api/v1/questions
/api/v1/questions/<id>

Now hook this up to React!

Data component

View
component

class List extends React.Component {
  render() {
    const { entities } = this.props.data

    if (!entities) {
      return ( <div>Loading...</div> )
    }

    return (
      <ul>
        {entities.entities.map((entity, i) =>
          <Question key={i} title={entity.title} />)
        }
      </ul>
    )
  }
}

const Query = gql`query Items {
  entities {
    entities {
      ... on Object {
        guid
        title
      }
    }
  }
}`

const ListWithData = graphql(Query)(List)

So GraphQL...

  • Allows a client to request a specific set of (nested) fields
  • Adds more structure to your API
  • Is introspectable
  • Is easily integratable with React

There is much more to discover

  • Type system
  • Fragments
  • Mutations
  • Optimistic UI

Questions?

  • slides.com/bartj/react-js-graphql
  • github.com/bartj/reactjs-graphql-talk
  • facebook.github.io/react
  • graphql.org
  • dev.apollodata.com

React.js & GraphQL

By bartj

React.js & GraphQL

  • 379