npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-component-data

v0.1.2

Published

React Component Data

Downloads

3

Readme

🍯 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);

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.