Skip to content

Commit c06d37a

Browse files
binoy14piotrwitek
authored andcommitted
Added example for using context in class component (piotrwitek#141)
Fixes piotrwitek#140 Let me know if it looks good or I need to make any changes. Thanks!
1 parent af7d940 commit c06d37a

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -845,6 +845,30 @@ export default function ToggleThemeButton(props: Props) {
845845

846846
```
847847
848+
#### ThemeConsumer in class component
849+
850+
```tsx
851+
import * as React from 'react';
852+
import ThemeContext from './theme-context';
853+
854+
type Props = {};
855+
856+
export class ToggleThemeButtonClass extends React.Component<Props> {
857+
static contextType = ThemeContext;
858+
context!: React.ContextType<typeof ThemeContext>;
859+
860+
render() {
861+
const { theme, toggleTheme } = this.context;
862+
return (
863+
<button style={theme} onClick={toggleTheme}>
864+
Toggle Theme
865+
</button>
866+
);
867+
}
868+
}
869+
870+
```
871+
848872
[Implementation with Hooks](#--usecontext)
849873
850874
[⇧ back to top](#table-of-contents)

README_SOURCE.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,10 @@ const mapDispatchToProps = (dispatch: Dispatch<ActionType>) => ({
319319
320320
::codeblock='playground/src/context/theme-consumer.tsx'::
321321
322+
#### ThemeConsumer in class component
323+
324+
::codeblock='playground/src/context/theme-consumer-class.tsx'::
325+
322326
[Implementation with Hooks](#--usecontext)
323327
324328
[⇧ back to top](#table-of-contents)
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import * as React from 'react';
2+
import ThemeContext from './theme-context';
3+
4+
type Props = {};
5+
6+
export class ToggleThemeButtonClass extends React.Component<Props> {
7+
static contextType = ThemeContext;
8+
context!: React.ContextType<typeof ThemeContext>;
9+
10+
render() {
11+
const { theme, toggleTheme } = this.context;
12+
return (
13+
<button style={theme} onClick={toggleTheme}>
14+
Toggle Theme
15+
</button>
16+
);
17+
}
18+
}

0 commit comments

Comments
 (0)