1 of 18

context & forms

React Week 09 (session 2)

2 of 18

01

02

03

04

05

06

07

Contextual cues

You createContext,�then useContext

Exercises!

Break!

Form & function

Exercises!

Exercise Walk Through

5 min

20 min

25 min

10 min

20 min

20 min

20 min

3 of 18

01 Contextual cues

4 of 18

createContext in context

const MyContext = createContext(<default>);

  • Generates a context object that can be used through a provider and useContext() to allow for shared state across an app
  • Normally default is not set - we set the initial data in the provider

5 of 18

MyContext.Provider in context

<MyContext.Provider value={initialValue}>...

  • Wraps its children providing a “location” to the value in MyContext

6 of 18

useContext in context

const value = useContext(MyContext);

  • Receives the value stored the context MyContext
  • This value can be received in any child component of <MyContext.Provider>...</MyContext.Provider>

7 of 18

02 You createContext,�then useContext

https://codesandbox.io/s/react-usecontext-themeswitcher-zi5mt

8 of 18

9 of 18

10 of 18

Break!

11 of 18

05 Form & function

12 of 18

<form>

<form onSubmit={...}>...</form>

  • a form, normally used to send data somewhere else, can also be used internally by our React app
  • onSubmit needs to preventDefault(); but how?

13 of 18

event.preventDefault()

onSubmit={(event) => { event.preventDefault(); … } }

  • This keeps our React page in the same place, preventing the default behavior (which is to change pages or post data out to a server)
  • event can be used to get the fields inside our form
    • But for that we need to assign names

14 of 18

Named <input>

<input name=”ourInputName”></input>

  • We can then access our value similar to JS by using event.target.ourInputName.value

https://codesandbox.io/s/react-form-namedinput-1ccjz

15 of 18

06 Handle your own form submissions

16 of 18

Exercise 2

(same as exercise 1, but with forms)

https://codesandbox.io/s/react-usecontext-exercise-randomapp-tfp4l

17 of 18

Live Coding Solution

18 of 18

Homework �