Skip to content

Instantly share code, notes, and snippets.

@MaximeHeckel
Last active March 27, 2018 01:58
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 MaximeHeckel/4fad17d99fbd920ff9d0ff4e2e5c9713 to your computer and use it in GitHub Desktop.
Save MaximeHeckel/4fad17d99fbd920ff9d0ff4e2e5c9713 to your computer and use it in GitHub Desktop.
React sub-components Take 2 - First sub-component example with the new context API
import React from "react";
// This creates the "Article Context" i.e. an object containing a Provider and a Consumer component
const ArticleContext = React.createContext();
// This is the Title sub-component, which is a consumer of the Article Context
const Title = () => {
return (
<ArticleContext.Consumer>
{({ title, subtitle }) => (
<div style={{ textAlign: "center" }}>
<h2>{title}</h2>
<div style={{ color: "#ccc" }}>
<h3>{subtitle}</h3>
</div>
</div>
)}
</ArticleContext.Consumer>
);
};
// This is our main Article components, which is a provider of the Article Context
const Article = props => {
return (
<ArticleContext.Provider {...props}>
{props.children}
</ArticleContext.Provider>
);
};
Article.Title = Title;
export default Article;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment