Permalink
Browse files

migrating to use react-context

  • Loading branch information...
davidchang committed Mar 3, 2018
1 parent 69da59a commit 7ccb4087bd21805689028accf19bdf6cfcd53a02
Showing with 103 additions and 48 deletions.
  1. +1 −0 package.json
  2. +1 −1 src/App.js
  3. +38 −0 src/DataConsumer.js
  4. +40 −0 src/DataProvider.js
  5. +0 −44 src/WrappedApp.js
  6. +11 −2 src/index.js
  7. +12 −1 yarn.lock
@@ -4,6 +4,7 @@
"private": true,
"homepage": "https://davidchang.github.io/redux-pokedex",
"dependencies": {
"create-react-context": "^0.2.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-scripts": "1.1.1"
@@ -9,7 +9,7 @@ function App({
}) {
return (
<section>
<h1>Pokedex in React state</h1>
<h1>Pokedex in React context</h1>

<form>
<div>
@@ -0,0 +1,38 @@
import React from 'react';
import { ThemeContext } from './DataProvider';

export default class DataConsumer extends React.Component {
render() {
const { children } = this.props;

return (
<ThemeContext.Consumer>
{({
caughtPokemon,
allPokemon,
searchTerm,
searchTermChanged,
markCaught,
}) => {
const pokemon = searchTerm
? allPokemon.filter(
pokemon =>
pokemon.name.toLowerCase().indexOf(searchTerm.toLowerCase()) >
-1,
)
: allPokemon;

return React.Children.map(children, child =>
React.cloneElement(child, {
caughtPokemon,
pokemon,
searchTerm,
searchTermChanged,
markCaught,
}),
);
}}
</ThemeContext.Consumer>
);
}
}
@@ -0,0 +1,40 @@
import React from 'react';
import Pokemon from './pokemon';
import App from './App.js';
import createReactContext from 'create-react-context';

const DEFAULT_STATE = {
caughtPokemon: [],
allPokemon: Pokemon,
searchTerm: '',
};

export const ThemeContext = createReactContext(DEFAULT_STATE);

export default class DataProvider extends React.Component {
state = DEFAULT_STATE;

searchTermChanged = searchTerm => {
this.setState({ searchTerm });
};

markCaught = newlyCaughtPokemon => {
this.setState({
caughtPokemon: [...this.state.caughtPokemon, newlyCaughtPokemon],
});
};

render() {
return (
<ThemeContext.Provider
value={{
...this.state,
searchTermChanged: this.searchTermChanged,
markCaught: this.markCaught,
}}
>
{this.props.children}
</ThemeContext.Provider>
);
}
}

This file was deleted.

Oops, something went wrong.
@@ -1,5 +1,14 @@
import React from 'react';
import ReactDOM from 'react-dom';
import WrappedApp from './WrappedApp';
import DataProvider from './DataProvider';
import DataConsumer from './DataConsumer';
import App from './App';

ReactDOM.render(<WrappedApp />, document.getElementById('root'));
ReactDOM.render(
<DataProvider>
<DataConsumer>
<App />
</DataConsumer>
</DataProvider>,
document.getElementById('root'),
);

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.

0 comments on commit 7ccb408

Please sign in to comment.