Advertisement
STANAANDREY

react-useContext

Aug 21st, 2021
1,601
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import './styles.css';
  2. import axios from 'axios';
  3. import React from 'react';
  4.  
  5. const themes = {
  6.     light: {
  7.         foreground: '#000000',
  8.         background: '#eeeeee'
  9.     },
  10.     dark: {
  11.         foreground: '#ffffff',
  12.         background: '#222222'
  13.     }
  14. };
  15. const ThemeContext = React.createContext();
  16.  
  17. export default function App() {
  18.     return (
  19.         <ThemeContext.Provider value={themes.dark}>
  20.             <Toolbar />
  21.             <b>not affected by theme</b>
  22.         </ThemeContext.Provider>
  23.     );
  24. }
  25.  
  26. function Toolbar(props) {
  27.     const theme = React.useContext(ThemeContext);
  28.     return (
  29.         <div style={{background: theme.background, color: theme.foreground}}>
  30.             <ThemedButton />
  31.             <AnotherComponent />
  32.             <p>a paragraph!</p>
  33.             <b>bold text</b>
  34.         </div>
  35.     );
  36. }
  37.  
  38. function AnotherComponent() {
  39.     return (
  40.         <div>
  41.             <ul>
  42.                 <li>1</li>
  43.                 <li>2</li>
  44.                 <li>3</li>
  45.             </ul>
  46.         </div>
  47.     );
  48. }
  49.  
  50. function ThemedButton() {
  51.     const theme = React.useContext(ThemeContext);
  52.     return (
  53.         <button
  54.             style={{
  55.                 background: theme.background,
  56.                 color: theme.foreground,
  57.                 border: '2px solid red',
  58.                 cursor: 'pointer'
  59.             }}>
  60.             I am styled by theme context!
  61.         </button>
  62.     );
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement