The awesome folks at Kadira have made an NPM module that let’s you create React containers and feed data into components.

When you are writing React components, a good way of making sure that your components are efficient is by removing as much state as possible and to only pass in the props that are needed. What you have left with is what is called a Dumb Component or a UI Component. So how do you actually get data into these components? Through Containers! Containers fetch data, and that’s about all they do.

A dumb component will have no dependencies on the rest of the app – you can easily plug and play with a dumb component and stick it just about anywhere. You will access all of the data in a dumb component via its props. Dan Abramov has a fantastic write up about the difference between smart and dumb components on Medium.

You can think of containers and smart components that are just wrappers for dumb components. To quote the React Komposer repo, containers usually do things like:

  • Request for data (invoke a subscription or just fetch it).
  • Show a loading screen while the data is fetching.
  • Once data arrives, pass it to the UI component.
  • If there is an error, show it to the user.
  • It may need to refetch or re-subscribe when props changed.
  • It needs to cleanup resources (like subscriptions) when the container is unmounting.

– The React Komposer README

React Komposer is Kadari’s answer to creating containers for your React components. After installing React Komposer with npm i --save react-komposer, you are able to compose React components with data.

Container Example

Let’s do a quick example using Komposer. We will simply display the user’s country using http://ipinfo.io. Let’s create a simple component:

const Country = ({country}) => (<div>{country}</div>);

Now let’s write our data grabbing function:

const composerFunction = (props, onData) => {
  $.get("http://ipinfo.io", function(response) {
      onData(null, {country:response.country});
  }, "jsonp");

  onData(null, {country:'Unknown'});
};

We used jQuery in the above code to ask ipinfo to give us some of the user’s locality information. This is a nice example of how we can update data since the get request is asynchronous.

All that’s left to do now is kompose and render:

// Compose the container
const CountryInfo = ReactKomposer.compose(composerFunction)(Country);

// Render the container
ReactDOM.render(<CountryInfo />, document.getElementById('react-root'));

You can see the live demo on JSFiddle here.