@@ -52,6 +52,7 @@ This gives you the power to prioritize our work and support the project contribu
52
52
- [ Render Props] ( #render-props ) 🌟 __ NEW__
53
53
- [ Higher-Order Components] ( #higher-order-components ) 📝 __ UPDATED__
54
54
- [ Redux Connected Components] ( #redux-connected-components )
55
+ - [ Context] ( #context )
55
56
- [ Hooks] ( #hooks )
56
57
- [ Redux] ( #redux )
57
58
- [ Action Creators] ( #action-creators ) 📝 __ UPDATED__
@@ -766,6 +767,98 @@ export default () => (
766
767
767
768
[⇧ back to top](#table-of-contents)
768
769
770
+ ## Context
771
+
772
+ > https://reactjs.org/docs/context.html
773
+
774
+ #### ThemeContext
775
+
776
+ ` ` ` tsx
777
+ import * as React from ' react' ;
778
+
779
+ export type Theme = React .CSSProperties ;
780
+
781
+ type Themes = {
782
+ dark: Theme ;
783
+ light : Theme ;
784
+ };
785
+
786
+ export const themes : Themes = {
787
+ dark: {
788
+ color: ' black' ,
789
+ backgroundColor: ' white' ,
790
+ },
791
+ light: {
792
+ color: ' white' ,
793
+ backgroundColor: ' black' ,
794
+ },
795
+ };
796
+
797
+ export type ThemeContextProps = { theme: Theme ; toggleTheme ?: () => void };
798
+ const ThemeContext = React .createContext <ThemeContextProps >({ theme: themes .light });
799
+
800
+ export default ThemeContext ;
801
+
802
+ ` ` `
803
+
804
+ [⇧ back to top](#table-of-contents)
805
+
806
+ #### ThemeProvider
807
+
808
+ ` ` ` tsx
809
+ import React from ' react' ;
810
+ import ThemeContext , { themes , Theme } from ' ./theme-context' ;
811
+ import ToggleThemeButton from ' ./theme-consumer' ;
812
+
813
+ interface State {
814
+ theme: Theme ;
815
+ }
816
+ export class ThemeProvider extends React .Component <{}, State > {
817
+ readonly state: State = { theme: themes .light };
818
+
819
+ toggleTheme = () => {
820
+ this .setState (state => ({
821
+ theme: state .theme === themes .light ? themes .dark : themes .light ,
822
+ }));
823
+ }
824
+
825
+ render() {
826
+ const { theme } = this .state ;
827
+ const { toggleTheme } = this ;
828
+ return (
829
+ <ThemeContext.Provider value = { { theme , toggleTheme }} >
830
+ <ToggleThemeButton />
831
+ </ThemeContext.Provider >
832
+ );
833
+ }
834
+ }
835
+
836
+ ` ` `
837
+
838
+ [⇧ back to top](#table-of-contents)
839
+
840
+ #### ThemeConsumer
841
+
842
+ ` ` ` tsx
843
+ import * as React from ' react' ;
844
+ import ThemeContext from ' ./theme-context' ;
845
+
846
+ type Props = {};
847
+
848
+ export default function ToggleThemeButton(props : Props ) {
849
+ return (
850
+ <ThemeContext.Consumer >
851
+ { ({ theme , toggleTheme }) => <button style = { theme } onClick = { toggleTheme } { ... props } />}
852
+ </ThemeContext.Consumer >
853
+ );
854
+ }
855
+
856
+ ` ` `
857
+
858
+ [Implementation with Hooks](#--usecontext)
859
+
860
+ [⇧ back to top](#table-of-contents)
861
+
769
862
## Hooks
770
863
771
864
> https://reactjs.org/docs/hooks-intro.html
0 commit comments