CodeBlanks Logo Icon CodeBlanks

Theme toggle

Learn the theme toggle button.

Theme toggle

The toggle switches between light and dark. When a button is pressed, the theme value changes; the Provider spreads the new value and all components update.

The switch is done with an expression like setTheme(theme === light ? dark : light). You call it in the button's onPress; the user switches the theme with one tap.

Toggle implementation

For a toggle you need theme and setTheme. You can get them with useContext(ThemeContext); or you can add a toggle function to the Provider value and spread it.

Example: const toggle = () => setTheme(theme === light ? dark : light). You pass this function to a Button's onPress. When the button is pressed, the theme changes at once.

Practice Add a toggle button

theme and setTheme are already taken with useContext(ThemeContext). Add a toggle button: const toggle = () => setTheme(theme === light ? dark : light) and <Button title="Switch" onPress={toggle} />. light and dark are defined.

Starter code

App.js
import React, { useContext } from 'react';
import { Button, Text, View } from 'react-native';

const light = { background: '#fff', text: '#000' };
const dark = { background: '#000', text: '#fff' };

const ThemeContext = React.createContext();

export default function App() {
  const { theme, setTheme } = useContext(ThemeContext);
  // Add a toggle button
  return (
    <View style={{ backgroundColor: theme.background }}>
      <Text style={{ color: theme.text }}>Theme</Text>
    </View>
  );
}

Sample solution

App.js
import React, { useContext } from 'react';
import { Button, Text, View } from 'react-native';

const light = { background: '#fff', text: '#000' };
const dark = { background: '#000', text: '#fff' };

const ThemeContext = React.createContext();

export default function App() {
  const { theme, setTheme } = useContext(ThemeContext);
  const toggle = () => setTheme(theme === light ? dark : light);
  return (
    <View style={{ backgroundColor: theme.background }}>
      <Text style={{ color: theme.text }}>Theme</Text>
      <Button title="Switch" onPress={toggle} />
    </View>
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the toggle concepts

Term Meaning
toggle Theme switch
setTheme Updates theme
light Light theme
dark Dark theme

2 What does the toggle button do?

  • Scrolls the list
  • Opens navigation
  • Generates a color
  • Switches between light and dark Correct answer

Explanation: The toggle switches between the light and dark themes.

3 Toggle expression

Question
const toggle = () => setTheme(theme === light ? ____ : light);
Answer
const toggle = () => setTheme(theme === light ? dark : light);

Explanation: If theme === light, switch to dark.

All lessons in Intermediate