From 5f7e10d09936d4bc42d69b02bd38711537a67136 Mon Sep 17 00:00:00 2001 From: Sosuke Suzuki Date: Sun, 27 Jan 2019 04:49:40 +0900 Subject: [PATCH 1/8] Modify to add Context API examples to README_SOURCe --- README_SOURCE.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/README_SOURCE.md b/README_SOURCE.md index b4d575d..6e7af6b 100644 --- a/README_SOURCE.md +++ b/README_SOURCE.md @@ -309,6 +309,30 @@ const mapDispatchToProps = (dispatch: Dispatch) => ({ [⇧ back to top](#table-of-contents) +## Context API + +> https://reactjs.org/docs/context.html + +#### ThemeContext + +::codeblock='playground/src/context/theme-context.ts':: + +[⇧ back to top](#table-of-contents) + +#### ThemeProvider + +::codeblock='playground/src/context/theme-provider.tsx':: + +[⇧ back to top](#table-of-contents) + +#### ThemeConsumer + +::codeblock='playground/src/context/theme-consumer.tsx':: + +[Implementation with Hooks](#hooks) + +[⇧ back to top](#table-of-contents) + ## Hooks > https://reactjs.org/docs/hooks-intro.html From 1f164f2f4da770cc3cdd37bedc40cb8ea3a2ac59 Mon Sep 17 00:00:00 2001 From: Sosuke Suzuki Date: Sun, 27 Jan 2019 04:49:58 +0900 Subject: [PATCH 2/8] Modify to generate new README.md --- README.md | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/README.md b/README.md index f5b8691..9599448 100644 --- a/README.md +++ b/README.md @@ -766,6 +766,98 @@ export default () => ( [⇧ back to top](#table-of-contents) +## Context API + +> https://reactjs.org/docs/context.html + +#### ThemeContext + +```tsx +import * as React from 'react'; + +export type Theme = React.CSSProperties; + +type Themes = { + dark: Theme; + light: Theme; +}; + +export const themes: Themes = { + dark: { + color: 'black', + backgroundColor: 'white', + }, + light: { + color: 'white', + backgroundColor: 'black', + }, +}; + +export type ThemeContextProps = { theme: Theme; toggleTheme?: () => void }; +const ThemeContext = React.createContext({ theme: themes.light }); + +export default ThemeContext; + +``` + +[⇧ back to top](#table-of-contents) + +#### ThemeProvider + +```tsx +import React from 'react'; +import ThemeContext, { themes, Theme } from './theme-context'; +import ToggleThemeButton from './theme-consumer'; + +interface State { + theme: Theme; +} +export class ThemeProvider extends React.Component<{}, State> { + readonly state: State = { theme: themes.light }; + + toggleTheme = () => { + this.setState(state => ({ + theme: state.theme === themes.light ? themes.dark : themes.light, + })); + } + + render() { + const { theme } = this.state; + const { toggleTheme } = this; + return ( + + + + ); + } +} + +``` + +[⇧ back to top](#table-of-contents) + +#### ThemeConsumer + +```tsx +import * as React from 'react'; +import ThemeContext from './theme-context'; + +type Props = {}; + +export default function ToggleThemeButton(props: Props) { + return ( + + {({ theme, toggleTheme }) =>