Context
React Week 10
What is Context?
What is context?
A simpler way to pass props to multiple children or down multiple levels.
Context Creation
You must import the createContext function from react (or accessed by React.createContext)
The context should be exported from the file in which is it created and imported to where ever is using it.
Context Providers
A context provider should wrap the components that you want to access the context.
Children even multiple levels deep can access the value provided.
Context Consumer
Any child that is descended from the provider can call the consumer and access the value passed.
Exercise
Task: Instead of passing username into each component, get username from context
Link to CodeSandBox - https://codesandbox.io/s/context-exercise-g24id
useContext
What is context?
A simpler way to pass props to multiple children or down multiple levels.
Context Provider and Creation
Same as previously!
Context Consumer
You must import { useContext } from 'react' and also the context from the context creation��Assign the returned value to your variable
Exercise
Task: replace <UsernameContext.Consumer> with useContext()��Link to CodeSandBox - https://codesandbox.io/s/context-exercise-forked-f50x6
Context for Theming
<ThemeProvider> from Styled Components
When using styled components, you can use react context in a hook provided by Styled Components.
This Theme object will then be accessible in any styled components component!
Context Provider and Creation
Similar to previously!
Instead import ThemeProvider from ‘styled-components’
It is common to wrap the entire app
Accessing Theme
It is automatically passed to every styled component!
Sehr Easy
Exercise
Link to CodeSandBox - https://codesandbox.io/s/context-exercise-with-usecontext-68tco
useContext for Theming
What if you want to know what the primary color is outside of styled components?
If you have a functional component, it is super easy!�
But I want to change the theme dynamically!!
Context Provider and Creation
OK, so don't wrap the whole App.�Wrap everything that should have your theme and keep the state of your theme there.��Make sure you give it a default theme to work with
Changing The Theme
Treat it the same as any other setState that you get passed
Exercise
Link to CodeSandBox - https://codesandbox.io/s/context-exercise-with-theme-forked-jxg5s
Resources
DOCS
Completed Exercise for if you get stuck
Link to CodeSandBox - https://codesandbox.io/s/context-exercise-with-theme-changer-66vi7?
Thank You!