Skip to content

Instantly share code, notes, and snippets.

@sarahsweat
Last active April 1, 2019 14:26
Show Gist options
  • Save sarahsweat/54f5ccc28adf82b3b4bf244a9331be09 to your computer and use it in GitHub Desktop.
Save sarahsweat/54f5ccc28adf82b3b4bf244a9331be09 to your computer and use it in GitHub Desktop.
ContextBlog
import React from 'react'
import styled from 'styled-components'
import Component2 from './component2'
const initialValue = {
message: "This is my message from context"
}
export const MyContext = React.createContext(initialValue)
export const Component1 = () => (
<MyContext.Provider value={initialValue}>
<HomeWrapper>
<h1>
This is Component 1
</h1>
<Component2 />
</HomeWrapper>
</MyContext.Provider>
)
const HomeWrapper = styled.div`
width: 550px;
padding: 10px;
text-align: center;
background-color: pink;
`
import React from 'react'
import Component3 from './component3'
const Component2 = props => {
return (
<>
<h2>Component 2</h2>
<Component3 />
</>
)
}
export default Component2
Component2.displayName = "Component2"
import React from 'react'
import { MyContext } from './Component1'
const Component3 = () => (
<MyContext.Consumer>
{({message}) => <>
<h3>Component 3</h3>
message: <h3>{message}</h3>
</>}
</MyContext.Consumer>
)
export default Component3
Component3.displayName = "Component3"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment