...

/

Theme Mode Selection Example

Theme Mode Selection Example

Learn about how context get implemented and targeted application to specific components or areas.

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:

Press + to interact
A theme made with light and dark options
A theme made with light and dark options

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 hook
const theme = useContext(ThemeContext);
return (
// Render a button with styling based on the current theme mode
<ButtonStyle mode={theme.mode}>
Ok
</ButtonStyle>
);
}
React button component with ThemeContext integration

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 mode
const color = props => (props.mode === 'light' ? 'black' : 'white');
// Set the text color using the 'color' function based on the provided theme mode
const ButtonStyle = styled.button`
color: ${color};
`;
Styled button component with dynamic text color based on theme mode

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 ...