1 of 43

#INCLUDE

Create For Community

Tech Cohort Workshop 4

INCLUDE

2 of 43

Agenda

In this workshop we will cover:

  • React.js
  • a bit of Next.js

INCLUDE

3 of 43

INCLUDE

React.js

4 of 43

Features

INCLUDE

Framework for web and mobile apps.

5 of 43

Components

INCLUDE

React allows you to divide your user interface into pieces, create them separately and then combine them together into a larger web page.

Functional Components: Javascript functions

  • parameters to func are optional
  • return value contains the HTML-style code to be rendered.
  • what we’ll be using

Class Components: Javascript classes

  • can exchange information with other class components
  • we will NOT use this

6 of 43

Example

INCLUDE

personal page:

About component:

Footer component:

Skills component:

Our cohort website :)

7 of 43

Importing and Exporting

INCLUDE

We want each component in a separate JSX file

  • Importing allows use of content from another file.
  • Exporting makes the file’s contents eligible for importing.

Example:

// in projectCard.jsx

export default function ProjectCard() {}

// in projects.jsx

import ProjectCard from “projectCard.jsx”

<ProjectCard/> //using imported component

8 of 43

INCLUDE

React Hooks

9 of 43

What is a Hook?

INCLUDE

Built-in React functions that allow functional components to use state, logic, and lots of other React features.

  • Always defined at the top level in functions
  • Important hooks: useState, useEffect, useRef, useContext, useMemo, useCallback

(logic) (UI)

component

Hook React Function

You have to import hooks to use them:

10 of 43

useState

INCLUDE

Used to track the “state” (data or property) in a functional component.

Essentially, treat it like a variable…

Syntax:

const [property, changeProperty] = useState(initialValue);

what you want to track

function to change the variable when triggered

(defined after this declaration)

what value you begin tracking from

11 of 43

useEffect

INCLUDE

Side-effects: logic that do not involve the output value.

without useEffect (BAD) with useEffect (good!)

useEffect() is used to separate the side-effect from the component rendering.

12 of 43

useEffect

INCLUDE

Syntax:

useEffect(callback, [dependencies,.. ]);

“callback” is a function that contains the logic of the side-effect

optional array that acts as a condition for when useEffect should be executed.

if dependencies change, useEffect is executed.

  • useEffect(callback); runs on every rerender
  • useEffect(callback, []); runs only on first rerender

13 of 43

useRef

INCLUDE

Used to

  • store values that can change
  • access elements

Different from state because:

  • changes don’t cause a re-render
  • in state, value changes after component re-rendering. in reference, the value is updated instantaneously.

refObject.current // access current value of the reference

14 of 43

useRef

INCLUDE

Example 1: storing values Example 2: accessing elements

15 of 43

useContext

INCLUDE

If many components of your app need some data, you can store it in a shared space (“context”).

Components anywhere can access context without traversing layers of components in the app.

Context can be created in any file in the project, but larger projects can benefit from a separate file for contexts.

Be sure to export a context for other components to import it.

https://dmitripavlutin.com/react-context-and-usecontext/

Data in the context has global scope.

16 of 43

useContext

INCLUDE

// creating context in component1.jsx

export const NameOfContext = createContext(DefaultValue);

// using NameOfContext in Component1

export default function Component1(){

const valueInContext = useContext(NameOfContext);

}

// using NameOfContext in Component2

import NameOfContext from ‘component1.jsx’;

export default function Component2(){

const valueInContext = useContext(NameOfContext);

}

17 of 43

useMemo

INCLUDE

Used to remember the output of an expensive computation between re-renders.

If the input for the computation does not change, useMemo allows you to skip doing the same computation again and gives the output.

18 of 43

useCallback

INCLUDE

Same feature as useMemo but for function

Remembers the function between renders. Function changes only if the dependencies change.

Often used when dealing with functions that are passed down to child components, especially to prevent unnecessary re-renders of those child components.

useCallback() returns a function.

useMemo() returns a value.

19 of 43

INCLUDE

State Updating

20 of 43

State Updating

State allows us to manage changing data in an application. It’s a way for a component to keep track of information that can change over time.

React allows us to update the value inside state using the setState function you define.

Recall that we define the first line within a component with a state variable and state setter function in the form of:

const[[state, setState] = useState(0);;

INCLUDE

21 of 43

State Updating

When updating a value, React triggers a re-render to update the UI.

IMPORTANT: When updating Objects & arrays held in a react state, NEVER change it directly. ALWAYS create a copy, modify it, and set state to your new copy.Updating objects/arrays:

*DON'T:

// UI won’t update correctly

form.firstName = 'Taylor';

DO:

setForm({

//create a new object with all the properties

// of the original

...form,

firstName: 'Taylor'

});

INCLUDE

const [form, setForm] = useState({

firstName: ‘’,

});

22 of 43

INCLUDE

Hands-On Exercises

23 of 43

INCLUDE

Object Deconstruction

24 of 43

Object Deconstruction

Destructuring is a JavaScript feature that allows us to extract multiple pieces of data from an array or object & assign them to our own variables

INCLUDE

25 of 43

INCLUDE

Props

26 of 43

Destructuring Props

Props is short for properties and refers to the information you send into a component. They are like arguments to a function

��

INCLUDE

Accessing props manually

��

Destructuring props in the parameter (most common)

��

Destructuring prop within component

��

27 of 43

Custom Props

Custom props refer to user-defined attributes that are passed from a parent to a child component.

—> Parents pass in props as attributes.

—> Children accept props as parameters.

INCLUDE

You can also define default values for props:

Child component receiving props greet, who:

Parent component passing in props greet, who:

28 of 43

Custom Props

There is no restriction on what value a prop can have. String, array, boolean, etc.

And say you wanted to pass down props, you can do so like this:

INCLUDE

Loop through each person in the array and render a Hello component for each one, passing it in as the “who” prop for the Hello component

29 of 43

Custom Props

And you can even use the spread operator to avoid naming all the possible props:

INCLUDE

Pass in each property from the hiBatman object as separate props

Pass all properties of hiBatman object in one step

30 of 43

INCLUDE

Node.js

31 of 43

Node

INCLUDE

  • npm install
    • Installs all dependencies listed in package.json

  • npm run dev
    • Starts the development server, if web page -> browser
    • Changes to code reflected immediately

  • npm run build
    • Checks for errors before deployment (PRs)

Node.js: A JavaScript runtime for building server-side applications.

npm (Node Package Manager): A tool to manage JavaScript libraries and dependencies.

32 of 43

INCLUDE

Next.js

33 of 43

Features

INCLUDE

Next.js is framework that builds on React and simplifies and accelerates React development.

Pages as Routes

  • Each file in the pages directory becomes a route.

Enhancing Performance:

  • Server-Side Rendering: improves initial load times by rendering pages on the server before sending to the browser.
  • Static Site Generation: generates static HTML at build time. serves pre-rendered pages.

34 of 43

Built-in Next.js Components

INCLUDE

Built-in features enhance performance and Search Engine Optimization.

<Image> : component for optimized image loading and lazy loading (only loads when it comes in the viewport).

<Image src="/path/to/image.jpg" alt="Description" width={500} height={300} />

HTML Equivalent = <img>

<Link> : component for client-side navigation between pages within the app.

<Link href="/about">About</Link>

HTML Equivalent = <a> with internal links (continue using <a> for external URLs)

<Head> : component for managing document head tags like title, meta, and links.

<Head> <title>Contact Us</title> </Head>

HTML Equivalent = <head>

35 of 43

<Image> Example

INCLUDE

<div className = {styles.imgContainer}>

<Image

src = "/path/to/image.jpg"

alt = "Description"

style = {{ objectFit: “cover”}}

fill = {true}

/>

</div>

  • fill: Image will fill parent element. If fill prop isn’t used, width and height are required
  • style: Pass CSS styles to image element
    • objectFit: “cover”: Image covers entire container (may stretch or cut off image)
    • objectFit: “contain”: maintain image aspect ratio (may not fill whole container)

  • Wrap <Image> in parent container!

36 of 43

INCLUDE

Optional Chaining

37 of 43

Optional Chaining

Optional chaining is a way for us to attempt to access object values and methods even if they may be undefined.

Optional chaining avoids throwing out errors.

Syntax reflects asking the program if the value exists:

INCLUDE

38 of 43

Optional Chaining

Let’s say you have multiple users, but not everyone will have subscriptions.

INCLUDE

39 of 43

Optional Chaining

Attempting to access values that don’t exist for all users will give us errors.

INCLUDE

40 of 43

Optional Chaining

However, optional chaining helps give us the option to define default values if attempting to access a value returns undefined.

INCLUDE

41 of 43

INCLUDE

Take Home Assignment

42 of 43

Create Your Navbar!

This week, you’ll be creating your navbar.

You are required to use useState for your navbar and the map function to create your dropDown items.

Reach out if you need any help and ask questions on Slack!

INCLUDE

43 of 43

INCLUDE

Thanks for Coming!!

Enjoy your Thanksgiving!