1 of 33

Intro to React

CSCI 338: Software Engineering

Fall 2024

1

2 of 33

Announcements

  • Project 1 due 1 week from today. I have only gotten 1 pull request – please make this a priority!
  • Lab 7 & 8 build on each other, and both are due next Sunday (11/17).
    • This gives you time to make Project 1 the priority.
  • This week + next Tuesday: Client-side engineering

2

3 of 33

Outline

  1. New JavaScript concepts
  2. Example of a React Application
  3. The rules of React

3

4 of 33

Outline

  1. New JavaScript concepts
  2. Example of a React Application
  3. The rules of React

4

5 of 33

What problems does React solve (Pros)?

Why would you want to use a client-side framework?

  1. Encourages you to abstract logical groupings of HTML, CSS and JavaScript logic into blocks (sometimes called ‘widgets’ or ‘components’)
  2. Standardizes the interfaces and techniques for handling workflow and user interactions (which makes it easier for teams to work together)
  3. Communities can organize around a library and make open-source components and plugins that can facilitate rapid prototyping.
  4. Helps to manage complexity as your app gets bigger.

5

6 of 33

Could it also make things harder (Cons)?

Why would you not want to use a client-side framework?

  1. Steep learning curve
  2. Might be overkill for what you need
    1. Sometimes all you need is a light-weight JS function to do the job!
    2. Useful if:
      • You’re making a bunch of server requests from a single-page application
      • You’ve got a lot of client-side components that you need to manage

6

7 of 33

A Few Notes on using JavaScript with React

A note on a few programming ideas / JavaScript

  1. Functional programming philosophy
  2. ES6 Modules
  3. Closures
  4. Object & array destructuring

7

8 of 33

1. Functional Programming v. OOP

  • A programming paradigm that relies on “pure functions” as much as possible
  • A pure function is one whose results are dependent only upon the input parameters, and whose operation initiates no side effect, that is, makes no external impact besides the return value.
  • Makes heavy use of immutability:
    • No variables are updated after they are assigned (makes code easier to reason about)
  • Functions are often passed in as data, and functions are also returned from functions.

8

9 of 33

2. ES6 Modules

  • Modules allow you to separate logical groupings of functionality, and given them a private scope (versus having everything on the global scope).
  • You can create public variables, functions, and objects using the “export” keyword. If you don’t use the “export” keyword, than the item is private.
  • You can also import modules and access them in other JavaScript files.
  • We will look at an example of a module shortly.

9

10 of 33

3. Closures

A closure gives you access to an outer function's scope from an inner function (see example). Used to encapsulate variable scope

10

function init() {

let name = "Walter"; // name is a local variable created by init

// inner function, that forms the closure

function displayName() {

console.log(name); // use variable declared in the parent function

}

displayName();

}

init(); // prints Walter

console.log(name); // throws an error

11 of 33

4. Destructuring: Objects

Object destructuring is just a shortcut for extracting object properties and assigning them to variables. Example:

const person = {

name: 'Alice',

age: 25,

city: 'Wonderland'

};

// Destructuring with curly braces

const { name, age } = person;

console.log(name); // Output: 'Alice'

console.log(age); // Output: 25

11

12 of 33

4. Destructuring: Arrays

Array destructuring is also a shortcut – for extracting array values and assigning them to variables. Example:

const numbers = [10, 48, 33];

// Destructuring with curly braces

const [ num1, num2, num3 ] = numbers;

console.log(num1); // Output: 10

console.log(num2); // Output: 48

console.log(num3); // Output: 33

12

13 of 33

Overview of React

  1. Lab 7
  2. Intro to JSX
  3. Components
  4. Event Handlers
  5. State management
  6. Effects

13

14 of 33

Overview of React

  1. Lab 7
  2. Intro to JSX
  3. Components
  4. Event Handlers
  5. State management
  6. Effects

14

15 of 33

Please pull the latest updates from class-exercises-fall2024 to your local computer

15

16 of 33

Discuss the Setup Process

  1. Installing dependencies
  2. What is vite doing (npm run dev)?
  3. What is a bundler?
  4. If React isn’t valid JavaScript, then how does the browser understand it?

Complete Steps 1-5, and then we will discuss.

16

17 of 33

Overview of React

  1. Lab 1
  2. Intro to JSX
  3. Components
  4. Event Handlers
  5. State management
  6. Effects

17

18 of 33

JSX

  1. A syntax extension to JavaScript
    1. Looks a lot like HTML with some small differences
    2. Works similarly to a template literal (backticks)
  2. Philosophy: Putting HTML & JS into the same file – via “components” – is easier to reason about. Keeping them separate is confusing.
  3. JSX not required, but suggested when using React. Example:

18

19 of 33

JSX Syntax

  1. camelCase convention for properties and variable names (just like JavaScript)
  2. No quotes around the JSX itself
  3. Quotes around constants
  4. Curly braces instead of quotes around JavaScript expressions
  5. Use “className” (instead of “class”) to assign CSS classes

19

<img className="thumbnail" src={post.image_url} />

20 of 33

JSX Example

<div className="post">

<h2>{post.user.username}</h2>

<img className="pic" src={post.image_url} />

<p>{post.last_updated}</p>

</div>

20

21 of 33

Overview of React

  1. Lab 7
  2. Intro to JSX
  3. Components
  4. Event Handlers
  5. State management
  6. Effects

21

22 of 33

React Components

  1. Allow you split the UI into independent, reusable pieces, and think about each piece in isolation (all JS frameworks do this, btw).
  2. A special kind of JavaScript function that:
    1. Accepts arbitrary inputs (called “props”)
    2. Returns a React element (JSX)
  3. All components must start with a capital letter (a naming convention that is enforced)
  4. Props – which are passed into the component – are read-only (immutable)

22

23 of 33

Component Rules

  1. Components accept an optional “props” object (optional)
  2. Components must return a JSX element

23

export function Welcome({name}) {�

// all components return JSX (a UI widget)

return <h1>Hello, {name}</h1>;

}

24 of 33

Using Components

Once you create a component function / class, you can use it like regular HTML syntax (so long as you import the component). Pretend you’re looking at the App.jsx file below:

// first import your component:

import Welcome from './Welcome';

export default function App(props) {

// You can use your component like a regular tag:

return <Welcome name="Sarah" />

}

24

25 of 33

Overview of React

  1. Lab 7
  2. Intro to JSX
  3. Components
  4. Event Handlers
  5. State management
  6. Effects

25

26 of 33

Handling Events

Take a look at the documentation.

<button onClick={sayHello}>Hi there</button>

26

27 of 33

Overview of React

  1. Lab 7
  2. Intro to JSX
  3. Components
  4. Event Handlers
  5. State management
  6. Effects

27

28 of 33

State and Lifecycle

  1. state variables must be declared for any variables whose changes to them might require a screen redraw
  2. All state variable changes trigger a request for the corresponding component to “redraw itself.” Examples of where you might want to use state:
    • A user likes or bookmarks a post
    • A user adds a new comment to the post
  3. When any of these interactions happens, you will update the component’s state…which will force a redraw.

28

29 of 33

Update State using the built-in useState() function

import { useState } from 'react';

function Carousel() {

const [index, setIndex] = useState(0); // pass in initial value

}

  • useState taks an initial value as an argument
  • Returns a list with two values: the current state and a setter function
  • See documentation: https://beta.reactjs.org/reference/react/useState

29

30 of 33

“State” Takeaways

  1. If you update a component’s state, this will automatically trigger a component redraw (for the associated component).
  2. See Lab Demo

30

31 of 33

“Lifting Up” State

  1. The state of a component is only accessible to the component (it’s encapsulated)!
  2. If you want a state change to “notify” another component (i.e. “lifting up the state”), then your child component needs to be granted access to a function that belongs to the parent of the component (passed to the child as a property)

31

32 of 33

Overview of React

  1. Lab 7
  2. Components
  3. Event Handlers
  4. State management
  5. Effects

32

33 of 33

Summary of Key Ideas in React

33

Components

Components are encapsulated units of logic that help you organize your code.

  • They can only access data that are passed in via props.
  • They return a JSX element

JSX

JSX is React’s version of HTML (see previous slides for syntax rules).

  • Any expression (a value or something that returns a value) can be embedded in JSX using curly braces.

Props

Props (properties) are read-only data fields that are passed into a component from its parent.

State

  • State variables are used when a change to a component’s data ought to trigger a redraw.
  • Use the useState function to generate the variable and a setter function
  • Every change to a state variable causes the component (and all of its child components) to redraw.