Skip to content

Instantly share code, notes, and snippets.

@Samsinite
Last active February 7, 2019 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Samsinite/cff76a6d94531e6b2b0fe9592ffb8af6 to your computer and use it in GitHub Desktop.
Save Samsinite/cff76a6d94531e6b2b0fe9592ffb8af6 to your computer and use it in GitHub Desktop.
Higher Order Components

Higher Order Components

Higher Order Components (commonly refered to as HOC) is a function that takes a component as an argument and returns a new component, using the component passed to it to decorate or transform. See https://reactjs.org/docs/higher-order-components.html for Reacts documentation on higher order components for more details.

Exercise One

Using the function below that returns a mocked dataset, build a component inside of Cherish (and render using Cosmos for ease of development) that accepts this information as a parameter posts and renders the dataset inside of a List.

function fetchPosts() {
  return [
    {
      title: 'An awesome react post',
      body: 'React higher order components are awesome, check out more details at https://reactjs.org/docs/higher-order-components.html.'
    },
    {
      title: 'Hooks are cool too!',
      body: 'Hooks let you reuse state without needing to implement react class components, check out more detaiuls at https://reactjs.org/docs/hooks-intro.html.'
    },
    {
      title: 'Foo Bar',
      body: 'FooBar is awesome! Try mixing in a little Baz for more effect.'
    }
  ];
}

Example Cosmos render code (assuming the component built is called PostsList):

const posts = fetchPosts();
return (<PostsList posts={posts} />

Exercise Two

Build a higher order component that attaches the mocked posts using fetchPosts to the posts param on the component that was passed into it. Call this HOC inside of Cosmos for testing.

Example Cosmos render code (assuming the HOC component built is called connectPosts and the previous component is called PostsList:

const PostsListWithPosts = connectPosts(PostsList);
return (<PostsListWithPosts />);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment