Introduction to
web apps & React
Lesson 4: React Components
November 2019
Amsul Naeem
twitter.com/amsul_
slides.com/amsul
Component Composition
React Components
Component State
Component Lifecycle
Reusing Logic
Component Composition
- Hooks
- Handlers
- Computation
Reusing Markup
- Styling
- Layout semantics
DEMO
Component API
Component Composition
Prescriptive
- Simple props
- Example:
labelText
&value
- Example:
- Render props
- Example:
renderIcon
- Example:
Flexible
- Allowing arbitrary “children”
- Special prop:
children
- Special prop:
3 ways of composition
Component Composition
- Simple props
- Render props
- Children prop
Exercise 1
Component Composition
Refactor form to use composition:
- Share markup
- Share logic
- (Optional) Allow arbitrary icon rendered next to button label
Starting point:
- github.com/amsul/george-brown-course
- Under the
lesson-04
directory - Follow the
README
file
15 minute break
Controlled Components
Component State
Passing state down into child components
UNcontrolled Components
Passing state up into ancestor components
Exercise 2
Component State
Validate form fields:
- First name & last name
- Show error when blurred without content
- Hide error when focused
- (Optional) Hide error after 5 seconds
- Submit button
- Disable when any field is empty
-
HINT: Use
<ErrorMessage>
component
Starting point:
- 👉 Continue from previous exercise
5 minute break
Stages
Component Lifecycle
- Initial render
- Mount
- Bindings are set up
- Update renders
- Bindings are re-set if needed
- Unmount
- Bindings are un-set
Managing Side-effects
Component Lifecycle
The useEffect
hook:
- Setup function
- Cleanup function
- Dependencies array
DEMO
Exercise 3
Component Lifecycle
Handle online status in the form:
- Bind listener to online event
window.addEventListener('online', () => {})
- Bind listener to offline event
window.addEventListener('offline'
, () => {})
- Unbind listeners appropriately
- Show status before submit button
- (Optional) Disable submit button when offline
Starting point:
- 👉 Continue from previous exercise
End of Lesson
Lesson 4: React Components
November 2019
Amsul Naeem
twitter.com/amsul_
slides.com/amsul
Lesson 4: React Components
By amsul
Lesson 4: React Components
- 119