To declare global variables in React, we can use the React context API.
For instance, we write
const themes = {
light: {
foreground: "#000000",
background: "#eeeeee",
},
dark: {
foreground: "#ffffff",
background: "#222222",
},
};
const ThemeContext = React.createContext(themes.light);
class App extends React.Component {
render() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
}
to call React.createContext
to create the ThemeContext
.
Then we wrap ThemeContext.Provider
to let the Toolbar
component access the context values.
Then we use the useContext
hook to access the theme.light
value by writing
function Toolbar() {
const theme = useContext(ThemeContext);
return (
<button style={{ background: theme.background, color: theme.foreground }}>
I am styled by theme context!
</button>
);
}```
We call `useContext` with `ThemeContext` to get the value of `ThemeContext` as the value of `theme`.