Skip to content

🍯 Data fetching for server-rendered React applications.

License

Notifications You must be signed in to change notification settings

gragland/react-component-data

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🍯 React Component Data

Data fetching for server-rendered React applications. Components declare the data they'd like to receive as props. Plays nicely with React Router.

Usage

Install the package:

$ npm install react-component-data --save 

Component

The only change you need to make to your component is to give it a getData() static method which returns an object containing the props that it would like to receive. On server-side render (and subsequent client-side render/re-hydration) your component will get those props on its initial mount. If a component is not rendered server-side its props will be fetched asyncronously and you can manage your component's loading state however you wish.

import React from 'react';
    
class Component extends React.Component {

  static async getData(){
    const response = await fetchGithubRepos('gragland');
    return { projects: response.data };
  }
      
  static defaultProps = { projects: null };

  render() { 
    const projects = this.props.projects;

    { projects ? 
      <ProjectsList projects={projects} />
    :
      <LoadingSpinner />
    }
  }
}

If you don't use async/await just return a Promise.

static getData(){
  return new Promise((resolve, reject) => {
    fetchGithubRepos('gragland')
    .then((response) => {
      resolve({ projects: response.data });
    });
  });
}

We'll continue to use async/await in our examples but keep in mind that you can use standard Promises instead.

Server

On the server-side you use resolve() to fetch your component's data and then pass the resulting data object as a prop to <ComponentData>.

import React from 'react';
import { renderToStaticMarkup, renderToString } from 'react-dom/server';
import ComponentData, { resolve } from 'react-component-data';
import Layout from './Layout.js';
import App from './App.js';

express()
.get('/', async function (req, res) {

  const data = await resolve(App);

  const body = renderToString( 
    <ComponentData data={data}>
      <App /> 
    </ComponentData>
  );

  res.send(
    renderToStaticMarkup( <Layout body={body} /> )
  );

}).listen( ... );

Server (w/ React Router)

import React from 'react';
import { renderToStaticMarkup, renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import ComponentData, { resolve } from 'react-component-data'; 
import routes from './routes.js';
import Layout from './Layout.js';

express()
.use((req, res, next) => {
  match(
    { routes: routes, location: req.url }, 
    async (error, redirectLocation, renderProps) => {

      const data = await resolve(RouterContext, renderProps);

      const body = renderToString( 
        <ComponentData data={data}>
          <RouterContext {...renderProps} /> 
        </ComponentData>
      );

      res.send(
        renderToStaticMarkup( <Layout body={body} /> )
      );
    }
 );
}).listen( ... );

Entry

import React from 'react';
import ReactDOM from 'react-dom';
import ComponentData from 'react-component-data';
import App from './App.js';

ReactDOM.render(
  <ComponentData>
    <App />
  </ComponentData>,
  document.getElementById('app')
);

Entry (w/ React Router)

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, browserHistory } from 'react-router';
import ComponentData from 'react-component-data';
import routes from './routes';

ReactDOM.render(
  <ComponentData>
    <Router history={browserHistory} routes={routes} />
  </ComponentData>,
  document.getElementById('app')
);

🌀 Recursive Resolve (experimental)

If you have nested components with data dependencies then you can use the recursive resolve method. Rather then just resolve data for the top level component (or route component when used with React Router), it will recursively iterate through your entire component tree, resolving each component's data dependency and calling its componentWillMount lifecycle method before moving farther down the tree.

import ComponentData, { resolve } from 'react-component-data/recursive';

Usage is exactly the same as in the examples above, except that you'll also need to wrap each nested component that expects data with our withData() Higher Order Component like so:

import { withData } from 'react-component-data';

class NestedComponent extends React.Component { 
  ...
}

export default withData(NestedComponent);

Demo

unsplash.now.sh (source)

Acknowledgements

  • Inspired by the very awesome Next.js framework by ▲ZEIT.
  • Much of the recursive resolver code was gratiously copied from the React Apollo project.

About

🍯 Data fetching for server-rendered React applications.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published