Theme Mode Selection Example
Learn about how context get implemented and targeted application to specific components or areas.
We'll cover the following...
Context is used for sharing site-wise information, but it can be also very effective in sharing things in a narrower area. In this lesson, we'll see examples of both cases.
Theme context
One nice and common usage involving a context is theming, which allows the user to switch between a light and dark theme based on their preference. See the image below:
To implement this feature, let's start with ThemeContext
:
const ThemeContext = React.createContext({mode: 'light', // or 'dark'})
We can set the default theme with an object supporting a mode
property, which is a string to hold either "light" or "dark".
Design theme context
Any component that requires the theme can read the settings from ThemeContext
. Let's build a theme-aware Button
component:
const Button = () => {// Access the current theme from the ThemeContext using useContext hookconst theme = useContext(ThemeContext);return (// Render a button with styling based on the current theme mode<ButtonStyle mode={theme.mode}>Ok</ButtonStyle>);}
We can theme the button's style based on the shared mode
inside the ButtonStyle
component:
// Define a function 'color' that determines text color based on the theme modeconst color = props => (props.mode === 'light' ? 'black' : 'white');// Set the text color using the 'color' function based on the provided theme modeconst ButtonStyle = styled.button`color: ${color};`;
ButtonStyle
is a styled component applied on top of the host button
component with modified CSS. It receives the mode
prop and, based on that, we can define ...