Last active
March 27, 2018 01:58
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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