Thinkster
React

Utilizing Component Inheritance

Learn how inheriting from other components allows you to reuse code, thus avoiding unnecessary code duplication

Valeri Karpov Up to date (Feb '17) React

This tutorial is a part of the "Build a Real World App with React & Redux" tutorial series.

One great feature of React components is that they're plain old JavaScript classes, which means that your components can inherit from other components. Let's see this in action in building the profile view. The profile view has 2 tabs - in this case, this 2nd tab will be a separate view that will inherit from the first one.

The ArticleList Reducer

For the profile page we're going to need to display a list of the user's articles. In order to do that, we need to decouple the ArticleList component from the home view's reducer. Let's write a separate 'articleList' reducer:

Create src/reducers/articleList.js
'use strict';

export default (state = {}, action) => {
  switch (action.type) {
    case 'HOME_PAGE_LOADED':
      return {
        ...state,
        articles: action.payload.articles,
        articlesCount: action.payload.articlesCount
      };
    case 'HOME_PAGE_UNLOADED':
      return {};
    case 'PROFILE_PAGE_LOADED':
    case 'PROFILE_FAVORITES_PAGE_LOADED':
      return {
        ...state,
        articles: action.payload[1].articles,
        articlesCount: action.payload[1].articlesCount
      };
    case 'PROFILE_PAGE_UNLOADED':
    case 'PROFILE_FAVORITES_PAGE_UNLOADED':
      return {};
  }

  return state;
};

Notice that we're also adding action handlers for the profile view and the profile favorites view, which is the second view that we'll be writing. In both cases we're just pulling the list of articles from the payload.

Next, let's change the home reducer so it doesn't do anything with the 'HOME_PAGE_LOADED' action:

src/reducers/home.js
export default (state = {}, action) => {
  switch (action.type) {
    case 'HOME_PAGE_UNLOADED':
      return {};
  }

  return state;
};

Finally, we need to tweak the MainView component to get the articles list from the 'articleList' reducer rather than the 'home' reducer.

src/Home/MainView.js
// ...

const mapStateToProps = state => ({
  ...state.articleList
});

// ...

Great, now the home view works as expected, and our 'articleList' reducer is hooked up to work with the Profile view. Let's get started on the Profile view.