Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Modify to generate new README.md
  • Loading branch information
sosukesuzuki committed Jan 26, 2019
commit 1f164f2f4da770cc3cdd37bedc40cb8ea3a2ac59
92 changes: 92 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<ThemeContextProps>({ 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 (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
<ToggleThemeButton />
</ThemeContext.Provider>
);
}
}

```

[⇧ 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 (
<ThemeContext.Consumer>
{({ theme, toggleTheme }) => <button style={theme} onClick={toggleTheme} {...props} />}
</ThemeContext.Consumer>
);
}

```

[Implementation with Hooks](#hooks)

[⇧ back to top](#table-of-contents)

## Hooks

> https://reactjs.org/docs/hooks-intro.html
Expand Down