From 8446b010c92b70eca2711a699c5b1dc81eea9cf5 Mon Sep 17 00:00:00 2001 From: Ken Date: Sat, 2 Mar 2019 22:56:59 -0800 Subject: [PATCH] adding step 2.4 and 2.5 exercises --- step2-04/exercise/README.md | 109 ++++++++++++++++++ step2-04/exercise/index.html | 11 ++ step2-04/exercise/src/TodoContext.ts | 4 + step2-04/exercise/src/components/TodoApp.tsx | 99 ++++++++++++++++ .../exercise/src/components/TodoFooter.tsx | 17 +++ .../exercise/src/components/TodoHeader.tsx | 64 ++++++++++ step2-04/exercise/src/components/TodoList.tsx | 21 ++++ .../exercise/src/components/TodoListItem.tsx | 76 ++++++++++++ step2-04/exercise/src/index.tsx | 10 ++ step2-04/exercise/src/store/index.ts | 14 +++ step2-05/exercise/README.md | 10 +- step2-05/exercise/src/index.tsx | 8 +- step2-05/exercise/src/reducers/index.ts | 12 +- 13 files changed, 440 insertions(+), 15 deletions(-) create mode 100644 step2-04/exercise/README.md create mode 100644 step2-04/exercise/index.html create mode 100644 step2-04/exercise/src/TodoContext.ts create mode 100644 step2-04/exercise/src/components/TodoApp.tsx create mode 100644 step2-04/exercise/src/components/TodoFooter.tsx create mode 100644 step2-04/exercise/src/components/TodoHeader.tsx create mode 100644 step2-04/exercise/src/components/TodoList.tsx create mode 100644 step2-04/exercise/src/components/TodoListItem.tsx create mode 100644 step2-04/exercise/src/index.tsx create mode 100644 step2-04/exercise/src/store/index.ts diff --git a/step2-04/exercise/README.md b/step2-04/exercise/README.md new file mode 100644 index 0000000..7f7360f --- /dev/null +++ b/step2-04/exercise/README.md @@ -0,0 +1,109 @@ +# Step 2.4 - React Context (Exercise) + +[Lessons](../) | [Exercise](./exercise/) | [Demo](./demo/) + +In this step, we describe some problems we encounter when creating a more complex application. + +We will solve these problems with the React Context API. The Context API consists of: + +1. Provider component +2. Consuming context from a Class Component +3. Consuming context from a Functional Component + +--- + +React represents a single component like this: + +``` +(props) => view; +``` + +In a real application, these functions are composed. It looks more like this: + +![](../../assets/todo-components.png) + +## Problems in a Complex Application + +1. Data needs to be passed down from component to component via props. Even when some components do not need to know about some data. This is a problem called **props drilling** + +2. There is a lack of coordination of changes that can happen to the data + +Even in our simple application, we saw this problem. For example, `` has this props interface: + +```ts +interface TodoListProps { + complete: (id: string) => void; + remove: (id: string) => void; + todos: Store['todos']; + filter: FilterTypes; + edit: (id: string, label: string) => void; +} +``` + +All of these props are not used, except to be passed down to a child Component, `TodoListItem`: + +```js + +``` + +## Context API + +Let's solve these problems with the React Context API. _context_ is React's way to share data from components to their descendant children components without explicitly passing down through props at every level of the tree. React context is created by calling `createContext()` with some initial data. Use the `` component to wrap a part of the component tree that should be handed the _context_. + +```js +// To create a completed empty context +const TodoContext = React.createContext(undefined); + +class TodoApp extends React.Component { + render() { + + // Pass in some state and function to the provider's value prop + return ( + +
+ + + +
+
+ ); + } +} +``` + +### Consume _context_ from a Class Component + +Inside the children components, like the `` component, the value can be access from the component's `context` prop like this: + +```js +class TodoHeader extends React.Component { + render() { + // Step 1: use the context prop + return
Filter is {this.context.filter}
; + } +} + +// Step 2: be sure to set the contextType property of the component class +TodoHeader.contextType = TodoContext; +``` + +### Consume _context_ from a Functional Component + +If you're using the functional component syntax, you can access the context with the `useContext()` function. `useContext()` requires a recent release of React (16.8): + +```js +const TodoFooter = props => { + const context = useContext(TodoContext); + return ( +
+ +
+ ); +}; +``` diff --git a/step2-04/exercise/index.html b/step2-04/exercise/index.html new file mode 100644 index 0000000..ee7d10d --- /dev/null +++ b/step2-04/exercise/index.html @@ -0,0 +1,11 @@ + + + + + + +
+
+ + + diff --git a/step2-04/exercise/src/TodoContext.ts b/step2-04/exercise/src/TodoContext.ts new file mode 100644 index 0000000..9ec0028 --- /dev/null +++ b/step2-04/exercise/src/TodoContext.ts @@ -0,0 +1,4 @@ +import React from 'react'; + +// The typing forces us to put something inside createContext(); start with undefined +export const TodoContext = React.createContext(undefined); diff --git a/step2-04/exercise/src/components/TodoApp.tsx b/step2-04/exercise/src/components/TodoApp.tsx new file mode 100644 index 0000000..971b527 --- /dev/null +++ b/step2-04/exercise/src/components/TodoApp.tsx @@ -0,0 +1,99 @@ +import React from 'react'; +import { Stack } from 'office-ui-fabric-react'; +import { TodoFooter } from './TodoFooter'; +import { TodoHeader } from './TodoHeader'; +import { TodoList } from './TodoList'; +import { Store } from '../store'; +import { TodoContext } from '../TodoContext'; + +let index = 0; + +export class TodoApp extends React.Component { + constructor(props) { + super(props); + this.state = { + todos: {}, + filter: 'all' + }; + } + render() { + return ( + + + + + + + + + + ); + } + + private _addTodo = label => { + const { todos } = this.state; + const id = index++; + + this.setState({ + todos: { ...todos, [id]: { label } } + }); + }; + + private _remove = id => { + const newTodos = { ...this.state.todos }; + delete newTodos[id]; + + this.setState({ + todos: newTodos + }); + }; + + private _complete = id => { + const newTodos = { ...this.state.todos }; + newTodos[id].completed = !newTodos[id].completed; + + this.setState({ + todos: newTodos + }); + }; + + private _edit = (id, label) => { + const newTodos = { ...this.state.todos }; + newTodos[id] = { ...newTodos[id], label }; + + this.setState({ + todos: newTodos + }); + }; + + private _clear = () => { + const { todos } = this.state; + const newTodos = {}; + + Object.keys(this.state.todos).forEach(id => { + if (!todos[id].completed) { + newTodos[id] = todos[id]; + } + }); + + this.setState({ + todos: newTodos + }); + }; + + private _setFilter = filter => { + this.setState({ + filter: filter + }); + }; +} diff --git a/step2-04/exercise/src/components/TodoFooter.tsx b/step2-04/exercise/src/components/TodoFooter.tsx new file mode 100644 index 0000000..80534f9 --- /dev/null +++ b/step2-04/exercise/src/components/TodoFooter.tsx @@ -0,0 +1,17 @@ +import React, { useContext } from 'react'; +import { DefaultButton, Stack, Text } from 'office-ui-fabric-react'; +import { TodoContext } from '../TodoContext'; + +export const TodoFooter = () => { + const context = useContext(TodoContext); + const itemCount = Object.keys(context.todos).filter(id => !context.todos[id].completed).length; + + return ( + + + {itemCount} item{itemCount === 1 ? '' : 's'} left + + context.clear()}>Clear Completed + + ); +}; diff --git a/step2-04/exercise/src/components/TodoHeader.tsx b/step2-04/exercise/src/components/TodoHeader.tsx new file mode 100644 index 0000000..f39d416 --- /dev/null +++ b/step2-04/exercise/src/components/TodoHeader.tsx @@ -0,0 +1,64 @@ +import React from 'react'; +import { Stack, Text, Pivot, PivotItem, TextField, PrimaryButton } from 'office-ui-fabric-react'; +import { FilterTypes } from '../store'; +import { TodoContext } from '../TodoContext'; + +interface TodoHeaderState { + labelInput: string; +} + +export class TodoHeader extends React.Component<{}, TodoHeaderState> { + constructor(props: {}) { + super(props); + this.state = { labelInput: undefined }; + } + + render() { + return ( + + + todos + + + + + ({ + ...(props.focused && { + field: { + backgroundColor: '#c7e0f4' + } + }) + })} + /> + + Add + + + + + + + + + ); + } + + private onAdd = () => { + this.context.addTodo(this.state.labelInput); + this.setState({ labelInput: undefined }); + }; + + private onChange = (evt: React.FormEvent, newValue: string) => { + this.setState({ labelInput: newValue }); + }; + + private onFilter = (item: PivotItem) => { + this.context.setFilter(item.props.headerText as FilterTypes); + }; +} + +TodoHeader.contextType = TodoContext; diff --git a/step2-04/exercise/src/components/TodoList.tsx b/step2-04/exercise/src/components/TodoList.tsx new file mode 100644 index 0000000..1033d8e --- /dev/null +++ b/step2-04/exercise/src/components/TodoList.tsx @@ -0,0 +1,21 @@ +import React, { useContext } from 'react'; +import { Stack } from 'office-ui-fabric-react'; +import { TodoListItem } from './TodoListItem'; +import { Store, FilterTypes } from '../store'; +import { TodoContext } from '../TodoContext'; + +export const TodoList = () => { + const context = useContext(TodoContext); + const { filter, todos } = context; + const filteredTodos = Object.keys(todos).filter(id => { + return filter === 'all' || (filter === 'completed' && todos[id].completed) || (filter === 'active' && !todos[id].completed); + }); + + return ( + + {filteredTodos.map(id => ( + + ))} + + ); +}; diff --git a/step2-04/exercise/src/components/TodoListItem.tsx b/step2-04/exercise/src/components/TodoListItem.tsx new file mode 100644 index 0000000..fa89047 --- /dev/null +++ b/step2-04/exercise/src/components/TodoListItem.tsx @@ -0,0 +1,76 @@ +import React from 'react'; +import { Stack, Checkbox, IconButton, TextField, DefaultButton } from 'office-ui-fabric-react'; +import { TodoContext } from '../TodoContext'; + +interface TodoListItemProps { + id: string; +} + +interface TodoListItemState { + editing: boolean; + editLabel: string; +} + +export class TodoListItem extends React.Component { + constructor(props: TodoListItemProps) { + super(props); + this.state = { editing: false, editLabel: undefined }; + } + + render() { + const { id } = this.props; + const { todos, complete, remove } = this.context; + + const item = todos[id]; + + return ( + + {!this.state.editing && ( + <> + complete(id)} /> +
+ + remove(id)} /> +
+ + )} + + {this.state.editing && ( + + + + + + Save + + + )} +
+ ); + } + + private onEdit = () => { + const { id } = this.props; + const { todos } = this.context; + const { label } = todos[id]; + + this.setState({ + editing: true, + editLabel: this.state.editLabel || label + }); + }; + + private onDoneEdit = () => { + this.context.edit(this.props.id, this.state.editLabel); + this.setState({ + editing: false, + editLabel: undefined + }); + }; + + private onChange = (evt: React.FormEvent, newValue: string) => { + this.setState({ editLabel: newValue }); + }; +} + +TodoListItem.contextType = TodoContext; diff --git a/step2-04/exercise/src/index.tsx b/step2-04/exercise/src/index.tsx new file mode 100644 index 0000000..2587243 --- /dev/null +++ b/step2-04/exercise/src/index.tsx @@ -0,0 +1,10 @@ +import React from 'react'; +import ReactDOM from 'react-dom'; +import { TodoApp } from './components/TodoApp'; +import { initializeIcons } from '@uifabric/icons'; + +// Initializes the UI Fabric icons that we can use +// Choose one from this list: https://developer.microsoft.com/en-us/fabric#/styles/icons +initializeIcons(); + +ReactDOM.render(, document.getElementById('app')); diff --git a/step2-04/exercise/src/store/index.ts b/step2-04/exercise/src/store/index.ts new file mode 100644 index 0000000..221b5f4 --- /dev/null +++ b/step2-04/exercise/src/store/index.ts @@ -0,0 +1,14 @@ +export type FilterTypes = 'all' | 'active' | 'completed'; + +export interface TodoItem { + label: string; + completed: boolean; +} + +export interface Store { + todos: { + [id: string]: TodoItem; + }; + + filter: FilterTypes; +} diff --git a/step2-05/exercise/README.md b/step2-05/exercise/README.md index 1cac395..630fa61 100644 --- a/step2-05/exercise/README.md +++ b/step2-05/exercise/README.md @@ -6,8 +6,12 @@ If you still have the app running from a previous step, stop it with `ctrl+c`. S 1. First, take a look at the store interface in `exercise/src/store/index.ts`. Note that the `Store` interface has two keys: `todos` and `filter`. We'll concentrate on `todos`, which is an object where the keys are string IDs and the values are of a `TodoItem` type. -2. Open `exercise/src/reducers/pureFunctions.ts` and fill in the missing function bodies. +2. Open `exercise/src/reducers/index.ts` and fill in the missing case statements for the switch on `action.type`. -3. Open `exercise/src/reducers/index.ts` and fill in the missing case statements for the switch on `action.type`. +3. Open `exercise/src/index.tsx` and write separate dispatch calls. -4. Open `exercise/src/reducers/pureFunctions.spec.ts` and implement tests for the functions you wrote for `remove`, `complete`, and `clear`. +4. Take a look what is written in the console (F12 on PC, cmd-option-I on Mac). + +5. Install the [Chrome](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd) or [Firefox](https://addons.mozilla.org/en-US/firefox/addon/reduxdevtools/) extensions + +6. Observe the state changes, try doing "time travel" diff --git a/step2-05/exercise/src/index.tsx b/step2-05/exercise/src/index.tsx index cca1020..5760af8 100644 --- a/step2-05/exercise/src/index.tsx +++ b/step2-05/exercise/src/index.tsx @@ -5,11 +5,7 @@ import { composeWithDevTools } from 'redux-devtools-extension'; const store = createStore(reducer, {}, composeWithDevTools()); -store.dispatch(actions.addTodo('hello')); - -let action = actions.addTodo('world'); -store.dispatch(action); - -store.dispatch(actions.remove(action.id)); +// TODO: try doing some store.dispatch() calls here +// HINT: remember to use the functions inside "actions" object console.log(store.getState()); diff --git a/step2-05/exercise/src/reducers/index.ts b/step2-05/exercise/src/reducers/index.ts index 3fac61f..eb294ac 100644 --- a/step2-05/exercise/src/reducers/index.ts +++ b/step2-05/exercise/src/reducers/index.ts @@ -6,7 +6,7 @@ export const todosReducer = createReducer( {}, { addTodo(state, action) { - state[action.id] = { label: action.label, completed: false }; + // TODO: implement this reducer }, remove(state, action) { @@ -14,10 +14,6 @@ export const todosReducer = createReducer( }, clear(state, action) { - state[action.id].completed = !state[action.id].completed; - }, - - complete(state, action) { Object.keys(state).forEach(key => { if (state[key].completed) { delete state[key]; @@ -25,8 +21,12 @@ export const todosReducer = createReducer( }); }, + complete(state, action) { + // TODO: implement this reducer + }, + edit(state, action) { - state[action.id].label = action.label; + // TODO: implement this reducer } } );