1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I...

22
Sally Kyvernitis (Temple University), page 1 1. GETTING STARTED USING REACT............................................................................................................................................................... 2 Using ES6 with React ......................................................................................................................................................................... 3 Using JSX with React ......................................................................................................................................................................... 4 JS File Naming and Organization in React Projects ........................................................................................................................... 4 2. EDITOR FOR REACT / JSX ........................................................................................................................................................................ 4 Using Visual Studio Code as React Editor .......................................................................................................................................... 5 3. REACT COMPONENTS ............................................................................................................................................................................. 6 4. REACT PROPERTIES................................................................................................................................................................................. 7 5. NESTED COMPONENTS............................................................................................................................................................................ 9 6. ITERATING OVER ARRAYS USING JAVASCRIPT MAP FUNCTION...................................................................................................................... 10 JavaScript Map Function Example Creating Image Tags................................................................................................................. 11 7. USING JAVASCRIPT TERNARY CONDITIONAL OPERATOR IN REACT COMPONENTS.............................................................................................. 12 8. REACT RE-RENDERS COMPONENTS WHEN THEIR STATE CHANGES................................................................................................................. 13 How to Declare a State Variable (What Do Square Brackets Mean?) ............................................................................................. 13 Example: Re-rendering a Component on State Change .................................................................................................................. 14 Example: Re-rendering Component, Passing Parameters to onClick (uses inline Arrow Fn) ........................................................... 15 9. MAKING AN AJAX CALL IN REACT ........................................................................................................................................................... 16 My AJAX Code.................................................................................................................................................................................. 17 10. WORKING WITH INPUT IN REACT .......................................................................................................................................................... 18 Surpressing Output .......................................................................................................................................................................... 19 Validation Only When Button Clicked ............................................................................................................................................. 19 React Objects as State Variables ..................................................................................................................................................... 21

Transcript of 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I...

Page 1: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 1

1. GETTING STARTED USING REACT............................................................................................................................................................... 2

Using ES6 with React ......................................................................................................................................................................... 3

Using JSX with React ......................................................................................................................................................................... 4

JS File Naming and Organization in React Projects ........................................................................................................................... 4

2. EDITOR FOR REACT / JSX ........................................................................................................................................................................ 4

Using Visual Studio Code as React Editor .......................................................................................................................................... 5

3. REACT COMPONENTS ............................................................................................................................................................................. 6

4. REACT PROPERTIES ................................................................................................................................................................................. 7

5. NESTED COMPONENTS ............................................................................................................................................................................ 9

6. ITERATING OVER ARRAYS USING JAVASCRIPT MAP FUNCTION ...................................................................................................................... 10

JavaScript Map Function Example Creating Image Tags................................................................................................................. 11

7. USING JAVASCRIPT TERNARY CONDITIONAL OPERATOR IN REACT COMPONENTS .............................................................................................. 12

8. REACT RE-RENDERS COMPONENTS WHEN THEIR STATE CHANGES ................................................................................................................. 13

How to Declare a State Variable (What Do Square Brackets Mean?) ............................................................................................. 13

Example: Re-rendering a Component on State Change .................................................................................................................. 14

Example: Re-rendering Component, Passing Parameters to onClick (uses inline Arrow Fn) ........................................................... 15

9. MAKING AN AJAX CALL IN REACT ........................................................................................................................................................... 16

My AJAX Code .................................................................................................................................................................................. 17

10. WORKING WITH INPUT IN REACT .......................................................................................................................................................... 18

Surpressing Output .......................................................................................................................................................................... 19

Validation Only When Button Clicked ............................................................................................................................................. 19

React Objects as State Variables ..................................................................................................................................................... 21

Page 2: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 2

1. Getting Started Using React

React is a JavaScript library for building web user interfaces. It was created by Facebook and a community of

contributors (open sourced in 2013). React is “everywhere” including PayPal, Airbnb, Apple, Microsoft, and (of course)

Facebook.

For a quick targeted introduction, skim all the React pages from my favorite web site:

https://www.w3schools.com/react/

Also, read this list of definitions/explanations from the official React site: https://reactjs.org/docs/glossary.html

Then come back and read this document while playing with the accompanied code samples. Refer to the w3Schools

React pages whenever you forget the meaning of some new concept. It will take some time immersing yourself in React

before things sink in and begin to seem “normal”.

After reading this document and playing with the accompanied code samples, I suggest you try looking at this link (I have

not looked at it yet): https://upmostly.com/tutorials/build-a-todo-app-in-react-using-hooks

Page 3: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 3

Using ES6 with React

Before learning React, you need to know the basics of HTML, CSS (which you already know), but also the new JavaScript

introduced by the latest ES6 specification). Read what w3Schools has to say about “React ES6”:

https://www.w3schools.com/react/react_es6.asp

In my React Sample code, there is a folder that tries to show the features of ES6 that are used extensively by React

coders. Here is a listing of the important new features of JavaScript (ES6):

o let and const (instead of var) for declarations.

With let, the scope of the variable is the block (not function) of the let statement (like java).

With const, you can declare a constant (with block scope). As the name implies, the value of the constant

cannot be changed. It is customary to use const when defining functions (since typically you don’t redefine

the functions).

o classes (very similar to java classes)

o arrow functions – they handle the keyword “this” differently than regular functions. If your function uses the “this”

keyword, whether or not to use an arrow function matters. For more on Arrow Functions:

https://codeburst.io/javascript-arrow-functions-for-beginners-926947fc0cdc

Regular Function Definition Using const Arrow Function Definition Using const

const increment = function (x) { x++; };

const increment = (x) => { x++;

};

o Object destructuring and array destructuring.

https://codeburst.io/a-pocket-guide-to-destructuring-assignment-in-es6-f89c172a00b9

let { a, b } = { b: "banana", a: "apple", c:"carrot" }; // ES6 object destructuring (assigns by property name)

console.log ("a is " + a + " and b is " + b); // prints “a is apple and b is banana”

let [ a, b ] = [ "apple", "banana", "carrot" ]; // ES6 array destructuring (assigns by position)

console.log ("a is " + a + " and b is " + b); // prints “a is apple and b is banana”

o You can use back tick to define multi-line strings which is really convenient when those strings contain HTML (which

may also have single or double quotes inside).

var message = `

<h1 id="welcome">Welcome</h1>

<p>We love having you here</p>

`;

o Template literals allowing embedded expressions.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

var who = "Sally";

var message = ` <h1 id="welcome">Welcome ${ who } </h1> `;

document.getElementById("root").innerHTML = message; // displays “Welcome Sally” on the page

Page 4: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 4

Using JSX with React

JSX (JavaScript as XML) is a JavaScript language extension that allows you to write HTML tags directly in JavaScript. The

highlighted code below is a simple example. This particular example is not impressive because if you just quoted the

highlighted code, you would not have to reference the JSX transformer. However, trust that writing JavaScript with

React is much easier when you use JSX.

function Hello( ) {

return (

<h1>Welcome to React</h1> // This line is JSX

);

}

In order to use JSX in your JavaScript, you have to

1. Provide a script tag that references the babel CDN

2. Make sure that the script tag (that surrounds your React/JS code) has type="text/babel".

JS File Naming and Organization in React Projects

I continue to assert that each JS file should be named the same as the single function (or object) defined inside – to help

you organize and find your JavaScript code. Also, since you must add the type="text/bable" attribute for script tags that

reference React/JSX components, it’s important to differentiate between React components and “regular JS files”. I

also wanted to distinguish between React components with and without UI. This is the organization I came up with:

Here’ s how you must reference a React/JSX component (from your index page):

<script type="text/babel" src="js/ReAct/AjaxTable.js"></script>

2. Editor For React / JSX

When writing React code with JSX, NetBean’s “Source – Format” (code indentation) does not work well. You can:

1. Indent your code manually (as I did for my code examples - it didn’t make me that crazy).

2. Keep using the NetBeans bundle to run your HTML pages through Apache, but use Visual Studio Code (or other

React friendly text editor, like Sublime Text) to edit your JavaScript files that have React Code and JSX in them.

Note: Visual Studio Code is small and open source, not to be confused with Visual Studio which is large and must be

purchased from Microsoft (unless you get a free copy because of being a Temple student).

These React components show up on a page somewhere.

The AjaxTable React component has no UI,

calls other React UI component(s).

These JS files have nothing to do with React. Their script tag

references do not need the type="text/babel" attribute.

Page 5: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 5

Using Visual Studio Code as React Editor

I found the (open source) Visual Studio Code installation quick and painless (and not huge). It was an easy adjustment to

start using it. Mostly we just need an editor that can format (indent) React code and identify React errors reliably.

Recommendation for using Visual Studio Code with React: https://www.robinwieruch.de/react-js-windows-

setup/ - but ignore all the initial talk about setting up a Node Package Manager (NPM) development

environment. We are going to keep things simple and use CDNs to reference the React libraries and to “compile”

React code. Remember that a CDN (Content Delivery Network)is just a hosted resource (like JS file or CSS file)

that our web pages can reference.

Download/Install Visual Studio Code. https://code.visualstudio.com/

In welcome/startup menu,

o Under “Tools and languages”, where it says “Install support for”, click on JavaScript and Typescript

o Then the Customize part of the Welcome screen should look like this (JavaScript and Typescript no

longer links because we already clicked on them).

If you need to bring up the welcome screen again, open the command panel (F1) and type “welcome”

o From the VS Code menu, click on “View – Extensions” to see which extensions were installed (or by

typing Shift + Command + p on a MAC).

o Then type “install ESLint” and try to install that plugin which will provide better error checking and

formatting for your React/JavaScript code.

o To format/indent your code in Visual Studio Code, type: Alt-Shift-F (the SAME keys that format in

NetBeans). To check or verify that this is right, select from menu: file – preferences – keyboard

shortcuts. Then type “format” into the search bar.

Type “install ESLint” here…

Page 6: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 6

3. React Components

A React component is a function that returns a single HTML element. All React components must start with a capital

letter (or you’ll see an error message in the Chrome F12 console). You use ReactDOM.render to place that component

somewhere on your page.

<!DOCTYPE html>

<html>

<head>

<!-- Reference the React CDNs (Content Delivery Networks, basically just a hosted web resource) -->

<script crossorigin src='https://unpkg.com/react@16/umd/react.development.js' crossorigin></script>

<script crossorigin src='https://unpkg.com/react-dom@16/umd/react-dom.development.js' crossorigin></script>

<!-- By referencing the Babel CDN, we can use JSX (HTML tags in JavaScript) -->

<script crossorigin src='https://unpkg.com/babel-standalone@6/babel.min.js' crossorigin></script>

</head>

<body>

<div id="root"></div>

<script type="text/babel">

function Hello() { // A React component, returns a single HTML element.

return (

<h1>Welcome to React</h1> // this is JSX because there are no quotes around the HTML code.

);

}

ReactDOM.render(

<Hello />, // references the component

document.getElementById("root")

);

</script>

</body>

</html>

Page 7: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 7

4. React Properties

You can send properties to a React component with syntax like HTML attributes. This makes the component more

reusable (and less “hard coded”). Note how you can use className="…" to link your React component to a CSS class for

the purposes of styling. React could not allow you to code class="…" because in JavaScript, class is a keyword.

<script type="text/babel">

function Hello (props) {

return (

<div className="heading">

<h1>Welcome to {props.library} </h1>

<p>{props.message}</p>

</div>

);

}

ReactDOM.render(

<Hello library="React" message="Have Fun!" />,

document.getElementById("root")

);

</script>

In the code above, ReactDOM.render invokes function hello, sending an object as input parameter like this:

Hello( { library:"React", message: "Have Fun!" } );

In function Hello, you didn’t have to name the input parameter props (although it is customary to do so). You could have

called it some other name, as long as you used that other name inside the <h1> and <p> tags.

Page 8: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 8

To pass a variable as a property to a React component, use curly braces like this:

const Hello = (props) => {

return (

<div className="heading">

<h1>Welcome to {props.library}</h1>

<p>{props.message}</p>

</div>

);

};

let myMessage = "You will love it";

ReactDOM.render(

<Hello library="React" message={myMessage} />,

document.getElementById("root")

);

If you use ES6 object destructuring in the input parameter of the component, the code looks cleaner, as shown below.

In either case (with or without destructuring), your component function (e.g., Hello) will reference the property names

(library and message in these examples).

<script type="text/babel">

function Hello ( {library, message} ) {

return (

<div className="heading">

<h1>Welcome to {library} </h1>

<p> {message} </p>

</div>

);

}

ReactDOM.render(

<Hello library="React" message="Have Fun!" />,

document.getElementById("root")

); </script>

Page 9: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 9

It is also customary for ES6 arrow functions to be used when defining components, like this:

Arrow function without destructuring Arrow function with destructuring

const Hello = (props) => { return ( <div className="heading"> <h1>Welcome to { props.library } </h1> <p> { props.message } </p> </div> ); };

const Hello = ( { library, message props } ) => { return ( <div className="heading"> <h1>Welcome to { library } </h1> <p> { message } </p> </div> ); };

5. Nested Components

In ReAct there is no problem having one component that’s built out of other components. See the example below of

how you can nest ReAct components.

<!DOCTYPE html>

<html>

<head>

<script crossorigin src='https://unpkg.com/react@16/umd/react.development.js' crossorigin></script>

<script crossorigin src='https://unpkg.com/react-dom@16/umd/react-dom.development.js' crossorigin></script>

<script crossorigin src='https://unpkg.com/babel-standalone@6/babel.min.js' crossorigin></script>

</head>

<body>

<div id="root"></div>

<script type="text/babel">

// uses neither arrow function nor destructuring

function Car (props) {

return <h4>{props.name}</h4>;

}

const App = ( ) => (

<div>

<Car name="Duster" />

<Car name="Prius" />

<Car name="Accord" />

</div>

);

ReactDOM.render(

<App />,

document.getElementById("root")

);

</script>

</body>

</html>

Page 10: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 10

6. Iterating Over Arrays Using JavaScript Map Function

JavaScript has a Map function (that’s used extensively in JavaScript functional programming) and here’s how it works:

https://www.w3schools.com/jsref/jsref_map.asp

// Function Math.sqrt is applied to every element in array numbers and returns array x as output.

function understandMap() {

var numbers = [4, 9, 16, 25];

var x = numbers.map(Math.sqrt);

console.log(x); // x is an array with values [2, 3, 4, 5]

}

You’ll see the map function used in React code like the example below. The input to cars.map is an inline arrow function

that names each element of (each object in) the car array to “car”, then converts each car object to an <li> tag.

Note that React wants every element created by map iteration to have a unique React “key” attribute (see highlighted

code below). So, to be able to use the map function effectively in React (to avoid React warnings), the objects in your

array need to have a unique property. This is the warning you’ll get otherwise (in the Chrome F12 console):

Warning: Each child in a list should have a unique "key" prop.

<script type="text/babel">

const carList = [

{id: 1, name: "Duster", year: 1980},

{id: 2, name: "Prius", year: 2010},

{id: 3, name: "Accord", year: 2019}

];

// you can rename mycar to anything else (like any input parameter), if you use that name consistently in the line below.

const App = ({cars}) => (

<ul>

{

cars.map(mycar =>

<li key={mycar.id} >{mycar.year} {mycar.name}</li>

)

}

</ul>

);

ReactDOM.render(

<App cars={carList} />,

document.getElementById("root")

);

</script>

Page 11: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 11

JavaScript Map Function Example Creating Image Tags

This is another example showing how to create one DOM element per item in an array using the JavaScript map

function. In this example, an image tag (with src attribute) is created for each item.

<script type="text/babel">

const userList = [

{

"webUserId": "4",

"userEmail": "[email protected]",

"image": "https://petapixel.com/assets/uploads/2017/01/Donald_Trump_official_portraitt.jpg"

},

{

"webUserId": "5",

"userEmail": "[email protected]",

"image": "https://i.pinimg.com/originals/55/08/a0/5508a0d858023e758892f09f35b53c93.jpg", }

];

const App = ({users}) => (

<div className="picDiv">

{

users.map(user =>

<p key={user.webUserId}> <img src={user.image} /> <br/> {user.userEmail} </p>

)

}

</div>

);

ReactDOM.render(

<App users={userList} />,

document.getElementById("root")

);

</script>

Page 12: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 12

7. Using JavaScript Ternary Conditional Operator in React Components

The following code shows how you can conditionally render elements using the JS ternary (conditional operator).

<div id="root"></div>

<script type="text/babel">

const itemList = [

{id: 1, name: "VolleyBall", price: "$20", qty: 0},

{id: 2, name: "BasketBall", price: "$15", qty: 5},

{id: 3, name: "Tennis Raquet", price: "$30", qty: 0},

{id: 4, name: "FootBall", price: "$40", qty: 10}

];

const Items = ({list}) => (

<ul>

{

list.map(ele =>

<li key={ele.id}>

{ele.name} costs {ele.price}, quantity: {ele.qty === 0? "out of stock" : ele.qty}

</li>

)

}

</ul>

);

ReactDOM.render(

<Items list={itemList} />,

document.getElementById("root")

);

</script>

For more about the JS ternary operator: https://www.w3schools.com/js/tryit.asp?filename=tryjs_comparison

Page 13: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 13

8. React Re-renders Components When Their State Changes

React components have a built-in state object where you can store variables that determine when the Component

should be re-rendered. When the state object changes, React re-renders the component.

Note: this document is handling React state using the new (November 2019) functional components using state hooks

which seem much simpler and more direct than the older method, where you had to use the “class extends React

Component”. I will not cover the older method, other than to show a few examples and suggest you not use them. I only

present these examples because the bulk of online documentation only discusses the older method.

How to Declare a State Variable (What Do Square Brackets Mean?)

If you want React to redisplay a component whenever a variable changes, declare that variable as a “state variable”.

For example, suppose you want your Counter component to redisplay itself whenever the variable “count” changes and

you want count’s initial value to be 0. You would declare “count” to be a state variable using syntax like this:

const [count, setCount] = useState(10);

The intention of the above code is that you are declaring a new state variable named “count” (with initial value 10) and

React is giving you a setter function (named setCount) to use when you want to change the value of count.

But, why the weird syntax? What does it mean? This JavaScript syntax is called “array destructuring”. It means that

React’s function useState is returning an array with two elements in it and those elements are being destructured into

two new variables: count and setCount. The blue code above is equivalent to the following code:

var stateArray = useState (initialValue); // Returns an array of two elements. In the example above initialValue was 10.

var count = stateArray [0]; // A state variable (named as you wanted) that controls redisplay of your component

// AND React’s useState function already set its value to be initialValue (count = 10)

var setCount = stateArray [1]; // React gave you a function to use when you want to modify the state variable, count

To reiterate, when we declare a state variable with React’s useState, it returns an array with two items. The first item is

a reference to the newly declared and initialized state variable, and the second is a function that lets us update the new

state variable. Instead of using syntax like the above (awkward and confusing) code, we use array destructuring (blue

code example). Note: React uses onClick whereas plain JavaScript uses onclick…

Page 14: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 14

Example: Re-rendering a Component on State Change

<!DOCTYPE html>

<html>

<head>

<!-- Reference the React CDNs (Content Delivery Networks, basically just a hosted web resource) -->

<script crossorigin src='https://unpkg.com/react@16/umd/react.development.js' crossorigin></script>

<script crossorigin src='https://unpkg.com/react-dom@16/umd/react-dom.development.js' crossorigin></script>

<script crossorigin src='https://unpkg.com/babel-standalone@6/babel.min.js' crossorigin></script>

</head>

<body>

<div id="output"></div>

<script type="text/babel">

const Counter = ( ) => {

// Declare a new state variable, which we'll call "count", initializing its value to 0.

// Then function setCount is given to us so we can use it to change the value of count.

const [count, setCount] = React.useState(0);

// Define local function that increments count using the setCount function provided to us by React

const inc = ( ) => {

setCount (count+1);

};

// Note that it is the React “onClick” not the JS “onclick”

return (

<div>

<p>You clicked {count} times</p>

<button onClick={ inc }> Click me </button>

</div>

);

};

ReactDOM.render(

<Counter />,

document.getElementById("output")

);

</script>

</body>

</html>

Page 15: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 15

Example: Re-rendering Component, Passing Parameters to onClick (uses inline Arrow Fn)

In order to have an event work with parameters, you can wrap the function call (that has parameters) with an

anonymous arrow function as shown below (highlighted).

<!DOCTYPE html>

<html>

<head>

<!-- Reference the React CDNs (Content Delivery Networks, basically just a hosted web resource) -->

<script crossorigin src='https://unpkg.com/react@16/umd/react.development.js' crossorigin></script>

<script crossorigin src='https://unpkg.com/react-dom@16/umd/react-dom.development.js' crossorigin></script>

<script crossorigin src='https://unpkg.com/babel-standalone@6/babel.min.js' crossorigin></script>

</head>

<body>

<div id="output"></div>

<script type="text/babel">

const Counter = ( ) => {

// Declare a new state variable, which we'll call "count", initializing its value to 1.

// Then function setCount is given to us so we can use it to change the value of count.

const [count, setCount] = React.useState(1);

const add = (howMuch) => {

setCount(count+howMuch);

};

return (

<div>

<p> Count is now {count} </p>

<button onClick={ ( ) => add(count) }> Double It </button>

&nbsp;

<button onClick={ ( ) => add(1) }> Add One to It </button>

</div>

);

};

ReactDOM.render(

<Counter />,

document.getElementById("output")

);

</script>

</body>

</html>

Page 16: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 16

9. Making an AJAX Call in React

This example shows how to make an ajax call. It needs to use state so that the component can be re-rendered based on

the results of the ajax call. Ajax is called using my (Sally’s) ajax function, but you could use jQuery or fetch instead… My

ajax code is on the next page, along with the json file that was read. To fit the code on the page, I deleted everything

above <body> (it is the same as the code on the previous page).

<body>

<div id="root"></div>

<script src="ajax_alt.js"></script>

<script type="text/babel">

const FoodList = ({list}) => (

<ul>

{

list.map(elem =>

<li key={elem.id}>{elem.name} costs {elem.price}</li>

)

}

</ul>

);

const FoodListComponent = ( ) => {

// Put array “items” into React’s state (with initial value empty array) and receive a setter function for that array.

const [items, setItems] = React.useState([]);

// Put string “error” into React’s state (with initial value null) and receive a setter function for that string.

const [error, setError] = React.useState(null);

// useEffect parameters. 2nd: array of “watch variables”, 1st: function to run whenever a watch variable changes.

React.useEffect( ( ) => {

ajax_alt("json/sk_foodItems.json",

function (obj) { setItems(obj.items); },

function (msg) { setError(msg); }

); // end of ajax call

}, // end of arrow function

[ ]); // second parameter of useEffect, no watch variables, means run once…

return (

<div>

{ error ? <div>Error: {error} </div> : <FoodList list={items} /> }

</div>

);

}; // class FoodListComponent

ReactDOM.render(

<FoodListComponent />,

document.getElementById("root")

);

</script>

</body>

</html>

Page 17: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 17

My AJAX Code

This ajax code was referenced by the code on the previous page.

// Make an ajax call to the given url. If the call was successful,

// invoke successFn (passing back the object JSON parsed from the ResponseText.

// Otherwise, invoke the failureFn passing an error message (string).

function ajax_alt (url, successFn, failureFn) {

var httpReq;

if (window.XMLHttpRequest) {

httpReq = new XMLHttpRequest(); //For Firefox, Safari, Opera

} else if (window.ActiveXObject) {

httpReq = new ActiveXObject("Microsoft.XMLHTTP"); //For IE 5+

} else {

alert('ajax not supported');

}

httpReq.open("GET", url); // specify which page you want to get

// Ajax calls are asyncrhonous (non-blocking). Specify the function you want

// your browser to run when the response (to the http request) is available.

httpReq.onreadystatechange = callBack;

httpReq.send(null); // initiate ajax call

function callBack( ) {

if (httpReq.readyState === 4) { // readyState == 4 means that the http request is complete

if (httpReq.status === 200) {

var jsObj = JSON.parse(httpReq.responseText);

console.log("ajax_alt success: will send obj (see next line)");

console.log(jsObj);

successFn(jsObj);

} else {

var eMsg = "Error (" + httpReq.status + " " + httpReq.statusText +

") while attempting to read '" + url + "'";

console.log("ajax_alt failure error is " + eMsg);

failureFn(eMsg);

}

}

} // end of callBack

} // end function ajax

Json/sk_foodItems.json (referenced by code on previous page):

{

"dbError:": "",

"items": [

{ "id": 1, "name": "Apples", "price": "$2" },

{ "id": 2, "name": "Bananas", "price": "$15" },

{ "id": 3, "name": "Peaches", "price": "$5" }

]

}

Page 18: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 18

10. Working With Input in React

This example shows how to get and utilize user input. This is a rudimentary example where the message changes with

every keystroke.

<body>

<div id="root"></div>

<script type="text/babel">

const GetInput = ( ) => {

const [nameInput, setNameInput] = React.useState(''); // '' is the initial value of the state variable

const [birthYearInput, setBirthYearInput] = React.useState(''); // '' is the initial state value

return (

<div>

Name: &nbsp; <input value={nameInput} onChange={e=>setNameInput(e.target.value)} />

&nbsp; &nbsp;

Birth Year <input value={birthYearInput} onChange={e=>setBirthYearInput(e.target.value)}/>

<h1>Welcome {nameInput}</h1>

<p>You were born in {birthYearInput}</p>

</div>

);

};

ReactDOM.render(

<GetInput />,

document.getElementById("root")

);

</script>

</body>

</html>

Page 19: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 19

Surpressing Output

In this example, there is no output until the user clicks the button, but then (like the previous example) the message

changes with every keystroke.

<div id="root"></div>

<script type="text/babel">

const InputMsg = () => {

const [nameInput, setNameInput] = React.useState(''); // '' is the initial value of the state variable

const [birthYearInput, setBirthYearInput] = React.useState(''); // '' is the initial state value

const [isSubmitted,setIsSubmitted] = React.useState(false);

return (

<div>

Name: <input value={nameInput} onChange={(e)=>setNameInput(e.target.value)} />

&nbsp;

Birth Year <input value={birthYearInput} onChange={(e)=>setBirthYearInput(e.target.value)}/>

&nbsp;

<button type="button" onClick={() => setIsSubmitted(true)} >Click Me (Button not Submit)</button>

{isSubmitted?

<div>

<h1>Welcome {nameInput}</h1>

<p>You were born in {birthYearInput}</p>

</div>

:

<div></div>

}

</div>

);

};

ReactDOM.render(

<InputMsg />,

document.getElementById("root")

);

</script>

Validation Only When Button Clicked

In the example on the next page, the validation messages are only displayed when the user clicks the button. As you

would expect, the error messages “jump around” depending on where the error is, then finally give an OK message if all

fields meet the validation criteria.

Page 20: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 20

<div id="root"></div>

<script type="text/babel">

const WelcomeForm = () => {

const [name, setName] = React.useState(''); // '' is the initial value of the state variable

const [nameMsg, setNameMsg] = React.useState(''); // '' is the initial value of the state variable

const [birthYear, setBirthYear] = React.useState(''); // '' is the initial state value

const [birthYearMsg, setBirthYearMsg] = React.useState(''); // '' is the initial state value

const [formMsg, setFormMsg] = React.useState(''); // '' is the initial state value

const validate = ( ) => {

var localNameMsg = "";

console.log("validate is running");

if (name.length === 0) {

localNameMsg="Required";

}

setNameMsg(localNameMsg);

var localBirthYearMsg = "";

if (birthYear.length === 0) {

localBirthYearMsg = "Required";

} else if (isNaN(birthYear)) {

localBirthYearMsg = "Please enter a number";

}

setBirthYearMsg(localBirthYearMsg);

var allMsgs = localNameMsg + localBirthYearMsg;

if (allMsgs.length ===0) {

setFormMsg("Thank you. Your input will be processed.");

} else {

setFormMsg("Please try again.");

}

};

return (

<div>

Name: <input value={name} onChange={(e)=>setName(e.target.value)} /> &nbsp;

{nameMsg} <br/><br/>

Birth Year <input value={birthYear} onChange={(e)=>setBirthYear(e.target.value)}/> &nbsp;

{birthYearMsg} <br/><br/>

<button type="button" onClick={ validate } >Click Me (Button not Submit)</button> <br/><br/>

{formMsg}

</div>

);

};

ReactDOM.render(

<WelcomeForm />,

document.getElementById("root")

);

Page 21: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 21

React Objects as State Variables

We can easily create an object as a React state variable, like this object named userData:

const [userData, setUserData] = React.useState( { name: "Sally", birthYear: "1997" } );

But if you just modify the object “the normal way”, React is not aware that the object changed and so does not update

the state variable and the component does not get re-rendered.

userData.birthYear = "2000"; // DOES NOT WORK TO UPDATE REACT’S STATE VARIABLE.

But these two lines of code WOULD WORK because they set userData to a new object.

userData = { name: "Sally", birthYear: "2000" };

userData = { name: userData.name, birthYear: "2000" };

But here is a more general solution that would work well, no matter how many properties the object has.

// This returns a new object that is a copy of the old object but with the propName property set to propValue.

const setProp = (obj, propName, propValue) => {

var o = Object.assign( { }, obj);

o[propName] = propValue;

return o;

}; // end of setProp

userData = setProp ( userData, "birthYear", "2000" );

On the next page, is a complete React component that does user input validation using an object to hold the user data and

another object to hold the related error messages.

Page 22: 1. U R 2. R O A U J S M F S T C O R C W T S C AJAX C R W I Rcis-linux2.temple.edu/~sallyk/tutorials_ReAct/React_Tutorial_SallyK.pdf · Sally Kyvernitis (Temple University), page 4

Sally Kyvernitis (Temple University), page 22

const ValidateForm = ( ) => {

// Create object containing user entered data into React State. Each property of the object is value attribute of a textbox.

const [userData, setUserData] = React.useState ({

name:"",

birthYear:""

});

// Create error message object into React State. Each property is related to the userData property of the same name.

const [errors, setErrors] = React.useState ({

name:"",

birthYear:"",

form:""

});

// See function setProp from previous page…

const validate = ( ) => { // client side validation…

var nameMsg = "";

if (userData.name.length === 0) {

nameMsg="Required";

}

var birthYearMsg = "";

if (userData.birthYear.length === 0) {

birthYearMsg = "Required";

} else if (isNaN(userData.birthYear)) {

birthYearMsg = "Please enter a number";

}

var formMsg = "Your input will be processed.";

var allMsgs = nameMsg + birthYearMsg;

if (allMsgs.length > 0) {

formMsg = "Please try again.";

}

setErrors ({

name:nameMsg,

birthYear:birthYearMsg,

form: formMsg

});

}; // end of function validate

return (

<div>

Name: <input value={userData.name} onChange=

{e=> setUserData(setProp(userData,"name", e.target.value)) } />

&nbsp; <span className="error">{errors.name}</span> <br/><br/>

Birth Year <input value={userData.birthYear} onChange=

{e=> setUserData( setProp(userData, "birthYear", e.target.value ) ) } />

&nbsp; <span className="error">{errors.birthYear}</span> <br/><br/>

<button type="button" onClick={ validate } >Click Me (Button not Submit)</button> <br/><br/>

<span className="msg">{errors.form}</span>

</div>

);

};