Last active
March 20, 2018 16:09
-
-
Save MaximeHeckel/f5d414d5625cde6aae417cc9e87ee0c5 to your computer and use it in GitHub Desktop.
React subcomponents with new context API (React 16.3.0-alpha.2)
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, { Component } from 'react'; | |
const ArticleContext = React.createContext(); | |
const OtherContext = React.createContext(); | |
const OutOfContextComponent = OtherContext.Provider; | |
const Article = ArticleContext.Provider; | |
const View = ArticleContext.Consumer; | |
const Title = () => { | |
// Trying to compose context consumers in this functional component | |
return ( | |
<ArticleContext.Consumer> | |
{({ title, subtitle }) => ( | |
<div | |
style={{ | |
align: "center" | |
}} | |
> | |
{title}-{subtitle} | |
<div> | |
<div> | |
<OtherContext.Consumer>{v => v}</OtherContext.Consumer> | |
</div> | |
</div> | |
</div> | |
)} | |
</ArticleContext.Consumer> | |
); | |
}; | |
const Metadata = () => { | |
// Wrapping the context consumer within a component | |
return ( | |
<ArticleContext.Consumer> | |
{({ left, right }) => ( | |
<div | |
style={{ | |
display: "flex", | |
justifyContent: "space-between" | |
}} | |
> | |
{left} | |
{right} | |
</div> | |
)} | |
</ArticleContext.Consumer> | |
); | |
}; | |
class App extends Component { | |
render() { | |
const content = { | |
title: <h1>React sub-components</h1>, | |
subtitle: <h2>test test test</h2>, | |
right: <h4>makes the code even better</h4>, | |
left: <h4>using the new context API</h4>, | |
text: <i>Hello world</i> | |
}; | |
return ( | |
<Article value={content}> | |
<OutOfContextComponent value="other context"> | |
<Title /> | |
</OutOfContextComponent> | |
<Metadata /> | |
{/* using the consumer as is*/} | |
<View>{val => <div>{val.text}</div>}</View> | |
</Article> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment