840
Video 3.1 React.js: Introduction Chris Murphy SD4x-3.1 1

Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

  • Upload
    buingoc

  • View
    214

  • Download
    2

Embed Size (px)

Citation preview

Page 1: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Video 3.1

React.js: Introduction

Chris Murphy

SD4x-3.1 1

Page 2: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Review

• JavaScript: a general-purpose, easy-to-use programming language

• DOM: representation of structure of HTML page, which can be manipulated using JavaScript

• jQuery: library that simplifies accessing/using the DOM

SD4x-3.1 2

Page 3: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

What is React?

• JavaScript library for building user interfaces

• HTML page is composed of recyclable, interactive ‘components’ that have a lifecycle during which the state of the component changes

• Highly efficient because of notion of VirtualDOM

• Created and maintained by Facebook

• Used in production by many well known companies

• Netflix

• WhatsApp, Instagram

• Atlassian(BitBucket, HipChat, Jira)

• Codecademy

• Airbnb

• Pinterest

• Dropbox

• PayPal

• Reddit

• Salesforce

• Squarespace

• New York Times

• Treehouse

• eBay

• Trulia

• Expedia

• Visa

• Wolfram Alpha

SD4x-3.1 3

Page 4: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Why React?

• Modularity: organize code into reusable components that can work together

• Lifecycle maintenance: modifying component based on state; event listeners; simplified conditional rendering

• JSX: write HTML within JavaScript

SD4x-3.1 4

Page 5: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Components

• Building blocks of React

• Make up the nodes included in the VirtualDOM

• Include and maintain a state that changes with events

• Each component maintains state independently

• Applications can be configured to respond to component level events

SD4x-3.1 5

Page 6: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

VirtualDOM

• Node tree that represents HTML elements, their attributes, and content as objects and properties

• Selectively renders and re-renders subtrees of nodes based on state changes

• Efficient because it does the least amount of DOM manipulation to update components

• Provides a layer of abstraction to the developer, providing simpler programming model and high performance

SD4x-3.1 6

Page 7: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Normal DOM – How it Works

• When a node is updated, the browser updates (re-renders) all nodes

SD4x-3.1 7

Page 8: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Normal DOM – How it Works

• When a node is updated, the browser updates (re-renders) all nodes

SD4x-3.1 8

Page 9: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Normal DOM – How it Works

• When a node is updated, the browser updates (re-renders) all nodes

Change has been made to any given

node

SD4x-3.1 9

Page 10: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Normal DOM – How it Works

• When a node is updated, the browser updates (re-renders) all nodes

Change has been made to any given

node

Re-render all nodes to reflect the change

SD4x-3.1 10

Page 11: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

VirtualDOM – How it Works

• When a node is updated, two things occur:

• ‘diff’ to determine which nodes within DOM have changed

• ‘reconciliation’ to update the nodes that are affected

SD4x-3.1 11

Page 12: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

VirtualDOM – How it Works

• When a node is updated, two things occur:

• ‘diff’ to determine which nodes within DOM have changed

• ‘reconciliation’ to update the nodes that are affected

Identify nodes that have changed

(‘diff’)

SD4x-3.1 12

Page 13: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

VirtualDOM – How it Works

• When a node is updated, two things occur:

• ‘diff’ to determine which nodes within DOM have changed

• ‘reconciliation’ to update the nodes that are affected

Identify nodes that have changed

(‘diff’)

Identify nodes that are affected by the

change (reconciliation)

SD4x-3.1 13

Page 14: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

VirtualDOM – How it Works

• When a node is updated, two things occur:

• ‘diff’ to determine which nodes within DOM have changed

• ‘reconciliation’ to update the nodes that are affected

Identify nodes that have changed

(‘diff’)

Identify nodes that are affected by the

change (reconciliation)

Re-render ONLY the nodes that were

affected by change

SD4x-3.1 14

Page 15: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Developing with React

1. Within the page’s HTML, allocate a position on the page in which the desired React component will be rendered, e.g. a div

2. Create a React component in JavaScript

• Establish an initial state

• Define any events that could change the component’s state over its lifecycle

• Define the function to render the HTML

3. Drop the component into position allocated in Step 1

SD4x-3.1 15

Page 16: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id="container"></div>

<script type="text/jsx">

<!-- Insert React code here -->

</script>

</body>

</html>

• Create a div in the HTML to represent the location where the React component will be placed

• Write JavaScript code to create and display component in div

SD4x-3.1 16

Page 17: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id="container"></div>

<script type="text/jsx">

<!-- Insert React code here -->

</script>

</body>

</html>

• Create a div in the HTML to represent the location where the React component will be placed

• Write JavaScript code to create and display component in div

SD4x-3.1 17

Page 18: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id="container"></div>

<script type="text/jsx">

<!-- Insert React code here -->

</script>

</body>

</html>

• Create a div in the HTML to represent the location where the React component will be placed

• Write JavaScript code to create and display component in div

SD4x-3.1 18

Page 19: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id="container"></div>

<script type="text/jsx">

<!-- Insert React code here -->

</script>

</body>

</html>

• Create a div in the HTML to represent the location where the React component will be placed

• Write JavaScript code to create and display component in div

SD4x-3.1 19

Page 20: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id="container"></div>

<script type="text/jsx">

<!-- Insert React code here -->

</script>

</body>

</html>

• Create a div in the HTML to represent the location where the React component will be placed

• Write JavaScript code to create and display component in div

SD4x-3.1 20

Page 21: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id="container"></div>

<script type="text/jsx">

<!-- Insert React code here -->

</script>

</body>

</html>

• Create a div in the HTML to represent the location where the React component will be placed

• Write JavaScript code to create and display component in div

SD4x-3.1 21

Page 22: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id="container"></div>

<script type="text/jsx">

<!-- Insert React code here -->

</script>

</body>

</html>

• Create a div in the HTML to represent the location where the React component will be placed

• Write JavaScript code to create and display component in div

SD4x-3.1 22

Page 23: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id="container"></div>

<script type="text/jsx">

<!-- Insert React code here -->

</script>

</body>

</html>

• Create a div in the HTML to represent the location where the React component will be placed

• Write JavaScript code to create and display component in div

SD4x-3.1 23

Page 24: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

JSX

• JSX – JavaScript XML Syntax Transform

• Allows user to write HTML-like tags within JavaScript

• Converts text (HTML) to React code

SD4x-3.1 24

Page 25: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Rendering Elements using JSX

<div id="container"></div>

<script type='text/jsx'>

ReactDOM.render(

<h1>Hello, World!</h1>,

document.getElementById('container')

);

</script>

SD4x-3.1 25

Page 26: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Rendering Elements using JSX

<div id="container"></div>

<script type='text/jsx'>

ReactDOM.render(

<h1>Hello, World!</h1>,

document.getElementById('container')

);

</script>

SD4x-3.1 26

Page 27: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Rendering Elements using JSX

<div id="container"></div>

<script type='text/jsx'>

ReactDOM.render(

<h1>Hello, World!</h1>,

document.getElementById('container')

);

</script>

SD4x-3.1 27

Page 28: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Rendering Elements using JSX

<div id="container"></div>

<script type='text/jsx'>

ReactDOM.render(

<h1>Hello, World!</h1>,

document.getElementById('container')

);

</script>

SD4x-3.1 28

Page 29: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Rendering Elements using JSX

<div id="container"></div>

<script type='text/jsx'>

ReactDOM.render(

<h1>Hello, World!</h1>,

document.getElementById('container')

);

</script>

SD4x-3.1 29

Page 30: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Rendering Elements using JSX

<div id="container"></div>

<script type='text/jsx'>

ReactDOM.render(

<h1>Hello, World!</h1>,

document.getElementById('container')

);

</script>

SD4x-3.1 30

Page 31: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Hello, React!

SD4x-3.1 31

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id='container'></div>

<script type='text/jsx'>

ReactDOM.render(

<h1> Hello, React! </h1>,

document.getElementById('container')

);

</script>

</body>

</html>

Page 32: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Hello, React!

SD4x-3.1 32

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id='container'></div>

<script type='text/jsx'>

ReactDOM.render(

<h1> Hello, React! </h1>,

document.getElementById('container')

);

</script>

</body>

</html>

Page 33: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Hello, React!

SD4x-3.1 33

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id='container'></div>

<script type='text/jsx'>

ReactDOM.render(

<h1> Hello, React! </h1>,

document.getElementById('container')

);

</script>

</body>

</html>

Page 34: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Hello, React!

SD4x-3.1 34

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id='container'></div>

<script type='text/jsx'>

ReactDOM.render(

<h1> Hello, React! </h1>,

document.getElementById('container')

);

</script>

</body>

</html>

Page 35: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Hello, React!

SD4x-3.1 35

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id='container'></div>

<script type='text/jsx'>

ReactDOM.render(

<h1> Hello, React! </h1>,

document.getElementById('container')

);

</script>

</body>

</html>

Page 36: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Hello, React!

SD4x-3.1 36

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id='container'></div>

<script type='text/jsx'>

ReactDOM.render(

<h1> Hello, React! </h1>,

document.getElementById('container')

);

</script>

</body>

</html>

Page 37: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Hello, React!

SD4x-3.1 37

<!DOCTYPE html>

<html>

<head>

<title>ReactJS Example</title>

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

<script src="react-dom.js"></script>

</head>

<body>

<div id='container'></div>

<script type='text/jsx'>

ReactDOM.render(

<h1> Hello, React! </h1>,

document.getElementById('container')

);

</script>

</body>

</html>

Page 38: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Looking Ahead

• Defining React components

• Reacting to user events

• Interaction between React components

• Developing large applications with React

SD4x-3.1 38

Page 39: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Looking Ahead

• Defining React components

• Reacting to user events

• Interaction between React components

• Developing large applications with React

SD4x-3.1 39

Page 40: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Video 3.2

React Components

Chris Murphy

SD4x-3.2 40

Page 41: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Review

• React allows us to create custom components and insert them into the VirtualDOM in our HTML page

• This allows for selective rendering and modular development of dynamic behavior

SD4x-3.2 41

Page 42: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

React Components

• Components are JavaScript objects based off the React.Component prototype

• Components define properties, event-based state variables, and callback functions

• A component’s render() function is used to render its HTML

• VirtualDOM manages each component’s lifecycle and calls its render() function as needed

SD4x-3.2 42

Page 43: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating React Components

• React.createClass() allows us to define a component

• This function takes an object containing the component’s specifications as an argument:

var HelloComponent = React.createClass ({

render: function() {

return (

<h1>Hello, React!</h1>

);

}

});

SD4x-3.2 43

Page 44: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating React Components

• React.createClass() allows us to define a component

• This function takes an object containing the component’s specifications as an argument:

var HelloComponent = React.createClass ({

render: function() {

return (

<h1>Hello, React!</h1>

);

}

});

SD4x-3.2 44

Page 45: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating React Components

• React.createClass() allows us to define a component

• This function takes an object containing the component’s specifications as an argument:

var HelloComponent = React.createClass ({

render: function() {

return (

<h1>Hello, React!</h1>

);

}

});

SD4x-3.2 45

Page 46: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating React Components

• React.createClass() allows us to define a component

• This function takes an object containing the component’s specifications as an argument:

var HelloComponent = React.createClass ({

render: function() {

return (

<h1>Hello, React!</h1>

);

}

});

SD4x-3.2 46

Page 47: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating React Components

• React.createClass() allows us to define a component

• This function takes an object containing the component’s specifications as an argument:

var HelloComponent = React.createClass ({

render: function() {

return (

<h1>Hello, React!</h1>

);

}

});

SD4x-3.2 47

Page 48: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating React Components

• React.createClass() allows us to define a component

• This function takes an object containing the component’s specifications as an argument:

var HelloComponent = React.createClass ({

render: function() {

return (

<h1>Hello, React!</h1>

);

}

});

SD4x-3.2 48

Page 49: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating React Components

• React.createClass() allows us to define a component

• This function takes an object containing the component’s specifications as an argument:

var HelloComponent = React.createClass ({

render: function() {

return (

<h1>Hello, React!</h1>

);

}

});

SD4x-3.2 49

Page 50: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating React Components

• React.createClass() allows us to define a component

• This function takes an object containing the component’s specifications as an argument:

var HelloComponent = React.createClass ({

render: function() {

return (

<h1>Hello, React!</h1>

);

}

});

SD4x-3.2 50

Page 51: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating React Components

• React.createClass() allows us to define a component

• This function takes an object containing the component’s specifications as an argument:

• Once we create the custom component, we can render it in the same way as HTML elements

var HelloComponent = React.createClass ({

render: function() {

return (

<h1>Hello, React!</h1>

);

}

});

ReactDOM.render(

<HelloComponent />,

document.getElementById('container')

);

SD4x-3.2 51

Page 52: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating React Components

• React.createClass() allows us to define a component

• This function takes an object containing the component’s specifications as an argument:

• Once we create the custom component, we can render it in the same way as HTML elements

var HelloComponent = React.createClass ({

render: function() {

return (

<h1>Hello, React!</h1>

);

}

});

ReactDOM.render(

<HelloComponent />,

document.getElementById('container')

);

SD4x-3.2 52

Page 53: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating React Components

• React.createClass() allows us to define a component

• This function takes an object containing the component’s specifications as an argument:

• Once we create the custom component, we can render it in the same way as HTML elements

var HelloComponent = React.createClass ({

render: function() {

return (

<h1>Hello, React!</h1>

);

}

});

ReactDOM.render(

<HelloComponent />,

document.getElementById('container')

);

SD4x-3.2 53

Page 54: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating React Components

• React.createClass() allows us to define a component

• This function takes an object containing the component’s specifications as an argument:

• Once we create the custom component, we can render it in the same way as HTML elements

var HelloComponent = React.createClass ({

render: function() {

return (

<h1>Hello, React!</h1>

);

}

});

ReactDOM.render(

<HelloComponent />,

document.getElementById('container')

);

SD4x-3.2 54

Page 55: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating React Components

• React.createClass() allows us to define a component

• This function takes an object containing the component’s specifications as an argument:

• Once we create the custom component, we can render it in the same way as HTML elements

var HelloComponent = React.createClass ({

render: function() {

return (

<h1>Hello, React!</h1>

);

}

});

ReactDOM.render(

<HelloComponent />,

document.getElementById('container')

);

SD4x-3.2 55

Page 56: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating Custom Components – ES6

• ES6 is a more recent version of JavaScript syntax

• We can define a class instead of a single object

class HelloComponent extends React.Component {

render() {

return (

<h1>Hello, React!</h1>

);

}

}

ReactDOM.render(

<HelloComponent />,

document.getElementById('container')

);

SD4x-3.2 56

Page 57: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating Custom Components – ES6

• ES6 is a more recent version of JavaScript syntax

• We can define a class instead of a single object

class HelloComponent extends React.Component {

render() {

return (

<h1>Hello, React!</h1>

);

}

}

ReactDOM.render(

<HelloComponent />,

document.getElementById('container')

);

SD4x-3.2 57

Page 58: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating Custom Components – ES6

• ES6 is a more recent version of JavaScript syntax

• We can define a class instead of a single object

class HelloComponent extends React.Component {

render() {

return (

<h1>Hello, React!</h1>

);

}

}

ReactDOM.render(

<HelloComponent />,

document.getElementById('container')

);

SD4x-3.2 58

Page 59: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating Custom Components – ES6

• ES6 is a more recent version of JavaScript syntax

• We can define a class instead of a single object

class HelloComponent extends React.Component {

render() {

return (

<h1>Hello, React!</h1>

);

}

}

ReactDOM.render(

<HelloComponent />,

document.getElementById('container')

);

SD4x-3.2 59

Page 60: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating Custom Components – ES6

• ES6 is a more recent version of JavaScript syntax

• We can define a class instead of a single object

class HelloComponent extends React.Component {

render() {

return (

<h1>Hello, React!</h1>

);

}

}

ReactDOM.render(

<HelloComponent />,

document.getElementById('container')

);

SD4x-3.2 60

Page 61: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating Custom Components – ES6

• ES6 is a more recent version of JavaScript syntax

• We can define a class instead of a single object

class HelloComponent extends React.Component {

render() {

return (

<h1>Hello, React!</h1>

);

}

}

ReactDOM.render(

<HelloComponent />,

document.getElementById('container')

);

SD4x-3.2 61

Page 62: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

React Component Attributes

• Properties

• Attributes and values that are set when the component is created

• Should never be modified after initialization

SD4x-3.2 62

Page 63: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

React Component Attributes

• Properties

• Attributes and values that are set when the component is created

• Should never be modified after initialization

• State

• Attributes and values that represent the current state of the component, based on what it does/represents

• Can be modified during the component’s lifecycle

SD4x-3.2 63

Page 64: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

React Component Attributes

• Properties

• Attributes and values that are set when the component is created

• Should never be modified after initialization

• State

• Attributes and values that represent the current state of the component, based on what it does/represents

• Can be modified during the component’s lifecycle

• Both properties and state can be used when rendering the component

SD4x-3.2 64

Page 65: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Properties

• Should always be assigned upon object creation, never modified afterward

• Component accesses its properties through this.props

SD4x-3.2 65

Page 66: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Properties

• Should always be assigned upon object creation, never modified afterward

• Component accesses its properties through this.props

ReactDOM.render(

<HelloUser name="Maria" />,

document.getElementById('container')

);

SD4x-3.2 66

Page 67: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Properties

• Should always be assigned upon object creation, never modified afterward

• Component accesses its properties through this.props

ReactDOM.render(

<HelloUser name="Maria" />,

document.getElementById('container')

);

SD4x-3.2 67

Page 68: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Properties

• Should always be assigned upon object creation, never modified afterward

• Component accesses its properties through this.props

ReactDOM.render(

<HelloUser name="Maria" />,

document.getElementById('container')

);

SD4x-3.2 68

Page 69: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Properties

• Should always be assigned upon object creation, never modified afterward

• Component accesses its properties through this.props

class HelloUser extends React.Component {

render() {

return (

<h1>Hello {this.props.name}!</h1>

);

}

}

ReactDOM.render(

<HelloUser name="Maria" />,

document.getElementById('container')

);

SD4x-3.2 69

Page 70: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Properties

• Should always be assigned upon object creation, never modified afterward

• Component accesses its properties through this.props

class HelloUser extends React.Component {

render() {

return (

<h1>Hello {this.props.name}!</h1>

);

}

}

ReactDOM.render(

<HelloUser name="Maria" />,

document.getElementById('container')

);

SD4x-3.2 70

Page 71: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Properties

• Should always be assigned upon object creation, never modified afterward

• Component accesses its properties through this.props

class HelloUser extends React.Component {

render() {

return (

<h1>Hello {this.props.name}!</h1>

);

}

}

ReactDOM.render(

<HelloUser name="Maria" />,

document.getElementById('container')

);

SD4x-3.2 71

Page 72: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Properties

• Should always be assigned upon object creation, never modified afterward

• Component accesses its properties through this.props

class HelloUser extends React.Component {

render() {

return (

<h1>Hello {this.props.name}!</h1>

);

}

}

ReactDOM.render(

<HelloUser name="Maria" />,

document.getElementById('container')

);

SD4x-3.2 72

Page 73: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Properties

• Should always be assigned upon object creation, never modified afterward

• Component accesses its properties through this.props

class HelloUser extends React.Component {

render() {

return (

<h1>Hello {this.props.name}!</h1>

);

}

}

ReactDOM.render(

<HelloUser name="Maria" />,

document.getElementById('container')

);

SD4x-3.2 73

Page 74: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Properties

• Should always be assigned upon object creation, never modified afterward

• Component accesses its properties through this.props

class HelloUser extends React.Component {

render() {

return (

<h1>Hello {this.props.name}!</h1>

);

}

}

ReactDOM.render(

<HelloUser name="Maria" />,

document.getElementById('container')

);

SD4x-3.2 74

Page 75: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Properties

• Should always be assigned upon object creation, never modified afterward

• Component accesses its properties through this.props

class HelloUser extends React.Component {

render() {

return (

<h1>Hello {this.props.name}!</h1>

);

}

}

ReactDOM.render(

<HelloUser name="Maria" />,

document.getElementById('container')

);

SD4x-3.2 75

Page 76: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Properties

• Should always be assigned upon object creation, never modified afterward

• Component accesses its properties through this.props

class HelloUser extends React.Component {

render() {

return (

<h1>Hello {this.props.name}!</h1>

);

}

}

ReactDOM.render(

<HelloUser name="Maria" />,

document.getElementById('container')

);

SD4x-3.2 76

Page 77: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Properties

• Should always be assigned upon object creation, never modified afterward

• Component accesses its properties through this.props

class HelloUser extends React.Component {

render() {

return (

<h1>Hello {this.props.name}!</h1>

);

}

}

ReactDOM.render(

<HelloUser name="Maria" />,

document.getElementById('container')

);

SD4x-3.2 77

Page 78: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component State

• The set of variables that can change during the component’s lifecycle

• Should be initialized in the constructor

• Component accesses its state through this.state

SD4x-3.2 78

Page 79: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 79

Page 80: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 80

Page 81: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 81

Page 82: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 82

Page 83: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 83

Page 84: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 84

Page 85: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 85

Page 86: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 86

Page 87: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 87

Page 88: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 88

Page 89: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 89

Page 90: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 90

Page 91: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 91

Page 92: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 92

Page 93: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 93

Page 94: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TimesViewed extends React.Component {

constructor(props) {

super(props);

var timesViewed = 0;

if (localStorage.timesViewed) {

timesViewed = localStorage.timesViewed;

}

timesViewed++;

this.state = { numViews: timesViewed };

localStorage.timesViewed = timesViewed;

}

render() {

return <b>{this.state.numViews}</b>;

}

}

ReactDOM.render(

<TimesViewed />,

document.getElementById('container')

);

SD4x-3.2 94

Page 95: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Lifecycle

• The React VirtualDOM invokes callback functions on components during their lifecycle

• These functions fall into three categories:

• Mounting

• Updating

• Unmounting

• You can optionally implement these for controlling the component

SD4x-3.2 95

Page 96: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Lifecycle: Mounting

• Called when a component is being created and added to the VirtualDOM

• constructor: creates component, initializes state based on properties

• componentWillMount: invoked before component is added to VirtualDOM

• componentDidMount: invoked after component has been added to VirtualDOM and has been rendered

SD4x-3.2 96

Page 97: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Lifecycle: Updating

• Called when a component’s props or state is changing and the component is re-rendered

• componentWillReceiveProps: invoked before receiving new props, e.g. when its parent component re-renders

• shouldComponentUpdate: can be used to determine whether to re-render

• componentWillUpdate: invoked before re-rendering after change to state

• componentDidUpdate: invoked after being re-rendered

SD4x-3.2 97

Page 98: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Component Lifecycle: Unmounting

• Called when a component is being removed from the VirtualDOM

• componentWillUnmount: invoked before component is removed from VirtualDOM and destroyed

SD4x-3.2 98

Page 99: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Summary

• React components are JavaScript objects that can be used as HTML elements in the VirtualDOM

• A component’s render() function is used to render its HTML

• A component’s properties are assigned when it is created

• A component’s state can change during its lifecycle

• A component’s lifecycle functions are invoked depending on relevant activities

SD4x-3.2 99

Page 100: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Video 3.3

React Events

Chris Murphy

SD4x-3.3 100

Page 101: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Review

• React allows us to insert JavaScript elements/components into VirtualDOM

• We can create additional components using the React.Component class as a base

• Components have two types of attributes

• Properties: set at initialization and immutable thereafter

• State: change in response to user events

• Component callback functions can be bound to HTML events

SD4x-3.3 101

Page 102: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Changing Component State

• A component’s state typically changes in response to some user action or “event”

• We can bind an event to a callback function within a React component

• That component can then change state using its setState function

• This will automatically re-render the component and any other affected component

SD4x-3.3 102

Page 103: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 103

Page 104: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 104

Page 105: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 105

Page 106: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 106

Page 107: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 107

Page 108: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 108

Page 109: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 109

Page 110: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 110

Page 111: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 111

Page 112: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 112

Page 113: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 113

Page 114: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 114

Page 115: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 115

Page 116: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 116

Page 117: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 117

Page 118: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 118

Page 119: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 119

Page 120: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 120

Page 121: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Counter extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

}

incrementCount() { // callback function

this.setState( { count: this.state.count + 1; } );

}

render() { // invoked when setState is called

return (

<div> Count: { this.state.count }

<button type="button"

onClick={ this.incrementCount.bind(this); } >

Increment

</button>

</div>

);

}

};

SD4x-3.3 121

Page 122: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 122

Page 123: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 123

Page 124: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 124

Page 125: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 125

Page 126: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 126

Page 127: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 127

Page 128: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 128

Page 129: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ReactDOM.render(

<div>

<LikeButton name="Java" />

<LikeButton name="JavaScript" />

</div>,

document.getElementById('container'));

SD4x-3.3 129

Page 130: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ReactDOM.render(

<div>

<LikeButton name="Java" />

<LikeButton name="JavaScript" />

</div>,

document.getElementById('container'));

SD4x-3.3 130

Page 131: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ReactDOM.render(

<div>

<LikeButton name="Java" />

<LikeButton name="JavaScript" />

</div>,

document.getElementById('container'));

SD4x-3.3 131

Page 132: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ReactDOM.render(

<div>

<LikeButton name="Java" />

<LikeButton name="JavaScript" />

</div>,

document.getElementById('container'));

SD4x-3.3 132

Page 133: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ReactDOM.render(

<div>

<LikeButton name="Java" />

<LikeButton name="JavaScript" />

</div>,

document.getElementById('container'));

SD4x-3.3 133

Page 134: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ReactDOM.render(

<div>

<LikeButton name="Java" />

<LikeButton name="JavaScript" />

</div>,

document.getElementById('container'));

SD4x-3.3 134

Page 135: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 135

Page 136: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 136

Page 137: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 137

Page 138: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 138

Page 139: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 139

Page 140: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 140

Page 141: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 141

Page 142: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 142

Page 143: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 143

Page 144: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 144

Page 145: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 145

Page 146: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 146

Page 147: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 147

Page 148: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 148

Page 149: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 149

Page 150: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 150

Page 151: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 151

Page 152: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 152

Page 153: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 153

Page 154: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 154

Page 155: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 155

Page 156: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 156

Page 157: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 157

Page 158: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 158

Page 159: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 159

Page 160: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 160

Page 161: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 161

Page 162: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 162

Page 163: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 163

Page 164: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 164

Page 165: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 165

Page 166: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class LikeButton extends React.Component {

constructor(props) {

super(props);

this.state = { liked : false };

}

toggle() {

this.setState( {liked: !this.state.liked} );

}

render() {

var name = this.props.name;

var txt = this.state.liked ? 'Unlike' : 'Like';

var myColor = this.state.liked ? 'red' : 'black';

var weight = this.state.liked ? 'bold' : 'normal';

return (

<p><span style={{color:myColor, fontWeight:weight }}>

{name} </span>

<span onClick={this.toggle.bind(this)}>

{'\ud83d\udc4d' + txt}

</span> </p> );

}

};

SD4x-3.3 166

Page 167: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 167

Page 168: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 168

Page 169: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 169

Page 170: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 170

Page 171: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.3 171

Page 172: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 172

Page 173: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 173

Page 174: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 174

Page 175: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 175

Page 176: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 176

Page 177: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 177

Page 178: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 178

Page 179: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 179

Page 180: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 180

Page 181: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 181

Page 182: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 182

Page 183: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 183

Page 184: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 184

Page 185: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

constructor(props) {

super(props);

this.state = { bold : false, color : 'black' };

}

handleMouseOver() {

this.setState( { bold : true } );

}

handleMouseOut() {

this.setState( { bold: false } );

}

handleClick() {

if (this.state.color == 'red' )

this.setState( { color: 'black' } );

else

this.setState( { color: 'red' } );

}

. . .

SD4x-3.3 185

Page 186: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

. . .

render () {

var myColor = this.state.color;

var weight = this.state.bold ? 'bold' : 'normal' ;

return (

<span style={ {color:myColor, fontWeight:weight} }

onClick={this.handleClick.bind(this)}

onMouseOver={this.handleMouseOver.bind(this)}

onMouseOut={this.handleMouseOut.bind(this)} >

{this.props.text}

</span>

);

}

};

ReactDOM.render(

<div><MyText text="Look at me!" /></div>,

document.getElementById('container')

);

SD4x-3.3 186

Page 187: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

. . .

render () {

var myColor = this.state.color;

var weight = this.state.bold ? 'bold' : 'normal' ;

return (

<span style={ {color:myColor, fontWeight:weight} }

onClick={this.handleClick.bind(this)}

onMouseOver={this.handleMouseOver.bind(this)}

onMouseOut={this.handleMouseOut.bind(this)} >

{this.props.text}

</span>

);

}

};

ReactDOM.render(

<div><MyText text="Look at me!" /></div>,

document.getElementById('container')

);

SD4x-3.3 187

Page 188: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

. . .

render () {

var myColor = this.state.color;

var weight = this.state.bold ? 'bold' : 'normal' ;

return (

<span style={ {color:myColor, fontWeight:weight} }

onClick={this.handleClick.bind(this)}

onMouseOver={this.handleMouseOver.bind(this)}

onMouseOut={this.handleMouseOut.bind(this)} >

{this.props.text}

</span>

);

}

};

ReactDOM.render(

<div><MyText text="Look at me!" /></div>,

document.getElementById('container')

);

SD4x-3.3 188

Page 189: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

. . .

render () {

var myColor = this.state.color;

var weight = this.state.bold ? 'bold' : 'normal' ;

return (

<span style={ {color:myColor, fontWeight:weight} }

onClick={this.handleClick.bind(this)}

onMouseOver={this.handleMouseOver.bind(this)}

onMouseOut={this.handleMouseOut.bind(this)} >

{this.props.text}

</span>

);

}

};

ReactDOM.render(

<div><MyText text="Look at me!" /></div>,

document.getElementById('container')

);

SD4x-3.3 189

Page 190: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

. . .

render () {

var myColor = this.state.color;

var weight = this.state.bold ? 'bold' : 'normal' ;

return (

<span style={ {color:myColor, fontWeight:weight} }

onClick={this.handleClick.bind(this)}

onMouseOver={this.handleMouseOver.bind(this)}

onMouseOut={this.handleMouseOut.bind(this)} >

{this.props.text}

</span>

);

}

};

ReactDOM.render(

<div><MyText text="Look at me!" /></div>,

document.getElementById('container')

);

SD4x-3.3 190

Page 191: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

. . .

render () {

var myColor = this.state.color;

var weight = this.state.bold ? 'bold' : 'normal' ;

return (

<span style={ {color:myColor, fontWeight:weight} }

onClick={this.handleClick.bind(this)}

onMouseOver={this.handleMouseOver.bind(this)}

onMouseOut={this.handleMouseOut.bind(this)} >

{this.props.text}

</span>

);

}

};

ReactDOM.render(

<div><MyText text="Look at me!" /></div>,

document.getElementById('container')

);

SD4x-3.3 191

Page 192: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

. . .

render () {

var myColor = this.state.color;

var weight = this.state.bold ? 'bold' : 'normal' ;

return (

<span style={ {color:myColor, fontWeight:weight} }

onClick={this.handleClick.bind(this)}

onMouseOver={this.handleMouseOver.bind(this)}

onMouseOut={this.handleMouseOut.bind(this)} >

{this.props.text}

</span>

);

}

};

ReactDOM.render(

<div><MyText text="Look at me!" /></div>,

document.getElementById('container')

);

SD4x-3.3 192

Page 193: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

. . .

render () {

var myColor = this.state.color;

var weight = this.state.bold ? 'bold' : 'normal' ;

return (

<span style={ {color:myColor, fontWeight:weight} }

onClick={this.handleClick.bind(this)}

onMouseOver={this.handleMouseOver.bind(this)}

onMouseOut={this.handleMouseOut.bind(this)} >

{this.props.text}

</span>

);

}

};

ReactDOM.render(

<div><MyText text="Look at me!" /></div>,

document.getElementById('container')

);

SD4x-3.3 193

Page 194: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

. . .

render () {

var myColor = this.state.color;

var weight = this.state.bold ? 'bold' : 'normal' ;

return (

<span style={ {color:myColor, fontWeight:weight} }

onClick={this.handleClick.bind(this)}

onMouseOver={this.handleMouseOver.bind(this)}

onMouseOut={this.handleMouseOut.bind(this)} >

{this.props.text}

</span>

);

}

};

ReactDOM.render(

<div><MyText text="Look at me!" /></div>,

document.getElementById('container')

);

SD4x-3.3 194

Page 195: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

. . .

render () {

var myColor = this.state.color;

var weight = this.state.bold ? 'bold' : 'normal' ;

return (

<span style={ {color:myColor, fontWeight:weight} }

onClick={this.handleClick.bind(this)}

onMouseOver={this.handleMouseOver.bind(this)}

onMouseOut={this.handleMouseOut.bind(this)} >

{this.props.text}

</span>

);

}

};

ReactDOM.render(

<div><MyText text="Look at me!" /></div>,

document.getElementById('container')

);

SD4x-3.3 195

Page 196: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

. . .

render () {

var myColor = this.state.color;

var weight = this.state.bold ? 'bold' : 'normal' ;

return (

<span style={ {color:myColor, fontWeight:weight} }

onClick={this.handleClick.bind(this)}

onMouseOver={this.handleMouseOver.bind(this)}

onMouseOut={this.handleMouseOut.bind(this)} >

{this.props.text}

</span>

);

}

};

ReactDOM.render(

<div><MyText text="Look at me!" /></div>,

document.getElementById('container')

);

SD4x-3.3 196

Page 197: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class MyText extends React.Component {

. . .

render () {

var myColor = this.state.color;

var weight = this.state.bold ? 'bold' : 'normal' ;

return (

<span style={ {color:myColor, fontWeight:weight} }

onClick={this.handleClick.bind(this)}

onMouseOver={this.handleMouseOver.bind(this)}

onMouseOut={this.handleMouseOut.bind(this)} >

{this.props.text}

</span>

);

}

};

ReactDOM.render(

<div><MyText text="Look at me!" /></div>,

document.getElementById('container')

);

SD4x-3.3 197

Page 198: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Summary

• We can bind user events in HTML elements to callback functions in React components

• When we invoke a component’s setStatefunction, the render function will automatically be called and the component’s appearance can change accordingly

SD4x-3.3 198

Page 199: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Video 3.4

React Component Interaction

Chris Murphy

SD4x-3.4 199

Page 200: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Review

• We can bind user events in HTML elements to callback functions in React components

• When we invoke a component’s setStatefunction, the render function will automatically be called and the component’s appearance can change accordingly

• Re-rendering one component may necessitate re-rendering others as well

SD4x-3.4 200

Page 201: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.4 201

Page 202: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.4 202

Page 203: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.4 203

Page 204: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 204

Page 205: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 205

Page 206: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 206

Page 207: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 207

Page 208: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 208

Page 209: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 209

Page 210: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 210

Page 211: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 211

Page 212: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 212

Page 213: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 213

Page 214: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 214

Page 215: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 215

Page 216: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 216

Page 217: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 217

Page 218: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 218

Page 219: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 219

Page 220: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 220

Page 221: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 221

Page 222: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

constructor(props) {

super(props);

var allItems = [ "Anteater", "Bear", "Cat",

"Dog", "Elephant" ];

this.state = { initialItems: allItems,

currentItems: allItems };

}

filterList(input) { // callback function

var updatedList = this.state.initialItems;

updatedList = updatedList.filter(function(item){

return item.search(input.target.value) !== -1;

});

this.setState( { currentItems: updatedList } );

}

. . .

SD4x-3.4 222

Page 223: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 223

Page 224: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 224

Page 225: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 225

Page 226: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 226

Page 227: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 227

Page 228: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 228

Page 229: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 229

Page 230: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 230

Page 231: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 231

Page 232: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 232

Page 233: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 233

Page 234: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 234

Page 235: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 235

Page 236: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 236

Page 237: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 237

Page 238: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 238

Page 239: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 239

Page 240: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 240

Page 241: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class FilteredList extends React.Component {

. . .

render(){

return (

<div><input type="text" placeholder="Search"

onChange={this.filterList.bind(this)}/>

<ListItems items={this.state.currentItems}/>

</div>

);

}

};

class ListItems extends React.Component {

render(){

return (

<ul> { this.props.items.map(function(item) {

return <li key={item}> {item} </li> } ) } </ul>

);

}

};

ReactDOM.render(<FilteredList/>,

document.getElementById('container'));

SD4x-3.4 241

Page 242: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.4 242

Page 243: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.4 243

Page 244: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.4 244

Page 245: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.4 245

Page 246: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.4 246

Page 247: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 247

Page 248: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 248

Page 249: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 249

Page 250: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 250

Page 251: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 251

Page 252: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 252

Page 253: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 253

Page 254: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 254

Page 255: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 255

Page 256: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 256

Page 257: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 257

Page 258: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 258

Page 259: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 259

Page 260: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 260

Page 261: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 261

Page 262: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 262

Page 263: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 263

Page 264: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 264

Page 265: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

constructor(props) {

super(props);

this.state = {items: [], text: ' ', id: 0};

}

handleChange(e) {

this.setState( { text: e.target.value } );

}

handleSubmit(e) {

e.preventDefault(); // so as not to reload the page

var newItem = { text: this.state.text,

id: this.state.id };

this.setState( {

items: this.state.items.concat(newItem),

text: ' ',

id: this.state.id + 1

});

}

SD4x-3.4 265

Page 266: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

. . .

render() {

return (

<div>

<h3>TO-DO LIST</h3>

<TodoList items={this.state.items} />

<form onSubmit={this.handleSubmit.bind(this)}>

<input onChange={this.handleChange.bind(this)}

value={this.state.text} />

<button>Add</button>

</form>

</div>

);

}

};

SD4x-3.4 266

Page 267: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

. . .

render() {

return (

<div>

<h3>TO-DO LIST</h3>

<TodoList items={this.state.items} />

<form onSubmit={this.handleSubmit.bind(this)}>

<input onChange={this.handleChange.bind(this)}

value={this.state.text} />

<button>Add</button>

</form>

</div>

);

}

};

SD4x-3.4 267

Page 268: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

. . .

render() {

return (

<div>

<h3>TO-DO LIST</h3>

<TodoList items={this.state.items} />

<form onSubmit={this.handleSubmit.bind(this)}>

<input onChange={this.handleChange.bind(this)}

value={this.state.text} />

<button>Add</button>

</form>

</div>

);

}

};

SD4x-3.4 268

Page 269: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

. . .

render() {

return (

<div>

<h3>TO-DO LIST</h3>

<TodoList items={this.state.items} />

<form onSubmit={this.handleSubmit.bind(this)}>

<input onChange={this.handleChange.bind(this)}

value={this.state.text} />

<button>Add</button>

</form>

</div>

);

}

};

SD4x-3.4 269

Page 270: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

. . .

render() {

return (

<div>

<h3>TO-DO LIST</h3>

<TodoList items={this.state.items} />

<form onSubmit={this.handleSubmit.bind(this)}>

<input onChange={this.handleChange.bind(this)}

value={this.state.text} />

<button>Add</button>

</form>

</div>

);

}

};

SD4x-3.4 270

Page 271: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

. . .

render() {

return (

<div>

<h3>TO-DO LIST</h3>

<TodoList items={this.state.items} />

<form onSubmit={this.handleSubmit.bind(this)}>

<input onChange={this.handleChange.bind(this)}

value={this.state.text} />

<button>Add</button>

</form>

</div>

);

}

};

SD4x-3.4 271

Page 272: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

. . .

render() {

return (

<div>

<h3>TO-DO LIST</h3>

<TodoList items={this.state.items} />

<form onSubmit={this.handleSubmit.bind(this)}>

<input onChange={this.handleChange.bind(this)}

value={this.state.text} />

<button>Add</button>

</form>

</div>

);

}

};

SD4x-3.4 272

Page 273: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

. . .

render() {

return (

<div>

<h3>TO-DO LIST</h3>

<TodoList items={this.state.items} />

<form onSubmit={this.handleSubmit.bind(this)}>

<input onChange={this.handleChange.bind(this)}

value={this.state.text} />

<button>Add</button>

</form>

</div>

);

}

};

SD4x-3.4 273

Page 274: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

. . .

render() {

return (

<div>

<h3>TO-DO LIST</h3>

<TodoList items={this.state.items} />

<form onSubmit={this.handleSubmit.bind(this)}>

<input onChange={this.handleChange.bind(this)}

value={this.state.text} />

<button>Add</button>

</form>

</div>

);

}

};

SD4x-3.4 274

Page 275: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoApp extends React.Component {

. . .

render() {

return (

<div>

<h3>TO-DO LIST</h3>

<TodoList items={this.state.items} />

<form onSubmit={this.handleSubmit.bind(this)}>

<input onChange={this.handleChange.bind(this)}

value={this.state.text} />

<button>Add</button>

</form>

</div>

);

}

};

SD4x-3.4 275

Page 276: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoList extends React.Component {

render() {

return (

<ul>

{this.props.items.map(function (item) {

return

<TodoItem id={item.id} text={item.text}/>

})}

</ul>

);

}

}

class TodoApp extends React.Component {

. . .

render() {

return (

. . .

<TodoList items={this.state.items} />

. . .

SD4x-3.4 276

Page 277: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoList extends React.Component {

render() {

return (

<ul>

{this.props.items.map(function (item) {

return

<TodoItem id={item.id} text={item.text}/>

})}

</ul>

);

}

}

class TodoApp extends React.Component {

. . .

render() {

return (

. . .

<TodoList items={this.state.items} />

. . .

SD4x-3.4 277

Page 278: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoList extends React.Component {

render() {

return (

<ul>

{this.props.items.map(function (item) {

return

<TodoItem id={item.id} text={item.text}/>

})}

</ul>

);

}

}

class TodoApp extends React.Component {

. . .

render() {

return (

. . .

<TodoList items={this.state.items} />

. . .

SD4x-3.4 278

Page 279: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoList extends React.Component {

render() {

return (

<ul>

{this.props.items.map(function (item) {

return

<TodoItem id={item.id} text={item.text}/>

})}

</ul>

);

}

}

class TodoApp extends React.Component {

. . .

render() {

return (

. . .

<TodoList items={this.state.items} />

. . .

SD4x-3.4 279

Page 280: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoList extends React.Component {

render() {

return (

<ul>

{this.props.items.map(function (item) {

return

<TodoItem id={item.id} text={item.text}/>

})}

</ul>

);

}

}

class TodoApp extends React.Component {

. . .

render() {

return (

. . .

<TodoList items={this.state.items} />

. . .

SD4x-3.4 280

Page 281: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoList extends React.Component {

render() {

return (

<ul>

{this.props.items.map(function (item) {

return

<TodoItem id={item.id} text={item.text}/>

})}

</ul>

);

}

}

class TodoApp extends React.Component {

. . .

render() {

return (

. . .

<TodoList items={this.state.items} />

. . .

SD4x-3.4 281

Page 282: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoList extends React.Component {

render() {

return (

<ul>

{this.props.items.map(function (item) {

return

<TodoItem id={item.id} text={item.text}/>

})}

</ul>

);

}

}

class TodoApp extends React.Component {

. . .

render() {

return (

. . .

<TodoList items={this.state.items} />

. . .

SD4x-3.4 282

Page 283: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoList extends React.Component {

render() {

return (

<ul>

{this.props.items.map(function (item) {

return

<TodoItem id={item.id} text={item.text}/>

})}

</ul>

);

}

}

class TodoApp extends React.Component {

. . .

render() {

return (

. . .

<TodoList items={this.state.items} />

. . .

SD4x-3.4 283

Page 284: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoList extends React.Component {

render() {

return (

<ul>

{this.props.items.map(function (item) {

return

<TodoItem id={item.id} text={item.text}/>

})}

</ul>

);

}

}

class TodoApp extends React.Component {

. . .

render() {

return (

. . .

<TodoList items={this.state.items} />

. . .

SD4x-3.4 284

Page 285: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoList extends React.Component {

render() {

return (

<ul>

{this.props.items.map(function (item) {

return

<TodoItem id={item.id} text={item.text}/>

})}

</ul>

);

}

}

class TodoApp extends React.Component {

. . .

render() {

return (

. . .

<TodoList items={this.state.items} />

. . .

SD4x-3.4 285

Page 286: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoList extends React.Component {

render() {

return (

<ul>

{this.props.items.map(function (item) {

return

<TodoItem id={item.id} text={item.text}/>

})}

</ul>

);

}

}

class TodoApp extends React.Component {

. . .

render() {

return (

. . .

<TodoList items={this.state.items} />

. . .

SD4x-3.4 286

Page 287: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoList extends React.Component {

render() {

return (

<ul>

{this.props.items.map(function (item) {

return

<TodoItem id={item.id} text={item.text}/>

})}

</ul>

);

}

}

class TodoApp extends React.Component {

. . .

render() {

return (

. . .

<TodoList items={this.state.items} />

. . .

SD4x-3.4 287

Page 288: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoList extends React.Component {

render() {

return (

<ul>

{this.props.items.map(function (item) {

return

<TodoItem id={item.id} text={item.text}/>

})}

</ul>

);

}

}

class TodoApp extends React.Component {

. . .

render() {

return (

. . .

<TodoList items={this.state.items} />

. . .

SD4x-3.4 288

Page 289: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 289

Page 290: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 290

Page 291: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 291

Page 292: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 292

Page 293: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 293

Page 294: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 294

Page 295: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 295

Page 296: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 296

Page 297: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 297

Page 298: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 298

Page 299: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 299

Page 300: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 300

Page 301: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 301

Page 302: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class TodoItem extends React.Component {

constructor(props) {

super(props);

this.state = { amDone: false };

}

handleClick() {

this.setState( { amDone: !this.state.amDone} );

}

render() {

var line = this.state.amDone ? 'line-through' : 'none';

return (

<li key={this.props.id}

onClick={this.handleClick.bind(this)}

style={{textDecoration:line}}>

{this.props.text} </li>

);

}

}

SD4x-3.4 302

Page 303: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Review

• React allows us to create reusable, modularized components that can be combined to form web applications

• React handles re-rendering of components based on the structure of VirtualDOM

SD4x-3.4 303

Page 304: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Video 3.5

React Component Interaction – part 2

Chris Murphy

SD4x-3.5 304

Page 305: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Review

• React allows us to create reusable, modularized components that can be combined to form web applications

• React handles re-rendering of components based on the structure of VirtualDOM

SD4x-3.5 305

Page 306: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.5 306

Page 307: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.5 307

Page 308: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.5 308

Page 309: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.5 309

Page 310: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.5 310

Page 311: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.5 311

Page 312: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.5 312

Page 313: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.5 313

Page 314: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.5 314

Page 315: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.5 315

Page 316: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.5 316

Page 317: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 317

Page 318: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 318

Page 319: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 319

Page 320: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 320

Page 321: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 321

Page 322: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 322

Page 323: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 323

Page 324: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 324

Page 325: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 325

Page 326: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 326

Page 327: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 327

Page 328: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 328

Page 329: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 329

Page 330: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 330

Page 331: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 331

Page 332: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 332

Page 333: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

constructor(props) {

super(props);

this.state = { input1: 0, input2: 0, product: 0 };

this.multiply = this.multiply.bind(this);

}

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 333

Page 334: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

render() {

return (

<div>

<NumberInputField id="1" action={this.multiply}/>

<NumberInputField id="2" action={this.multiply}/>

<OutputField product={this.state.product}/>

</div>

);

}

}

SD4x-3.5 334

Page 335: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

render() {

return (

<div>

<NumberInputField id="1" action={this.multiply}/>

<NumberInputField id="2" action={this.multiply}/>

<OutputField product={this.state.product}/>

</div>

);

}

}

SD4x-3.5 335

Page 336: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

render() {

return (

<div>

<NumberInputField id="1" action={this.multiply}/>

<NumberInputField id="2" action={this.multiply}/>

<OutputField product={this.state.product}/>

</div>

);

}

}

SD4x-3.5 336

Page 337: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

render() {

return (

<div>

<NumberInputField id="1" action={this.multiply}/>

<NumberInputField id="2" action={this.multiply}/>

<OutputField product={this.state.product}/>

</div>

);

}

}

SD4x-3.5 337

Page 338: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

render() {

return (

<div>

<NumberInputField id="1" action={this.multiply}/>

<NumberInputField id="2" action={this.multiply}/>

<OutputField product={this.state.product}/>

</div>

);

}

}

SD4x-3.5 338

Page 339: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

render() {

return (

<div>

<NumberInputField id="1" action={this.multiply}/>

<NumberInputField id="2" action={this.multiply}/>

<OutputField product={this.state.product}/>

</div>

);

}

}

SD4x-3.5 339

Page 340: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

render() {

return (

<div>

<NumberInputField id="1" action={this.multiply}/>

<NumberInputField id="2" action={this.multiply}/>

<OutputField product={this.state.product}/>

</div>

);

}

}

SD4x-3.5 340

Page 341: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

<NumberInputField id="1" action={this.multiply}/>

. . .

SD4x-3.5 341

class NumberInputField extends React.Component {

constructor(props) {

super(props);

this.handleChange = this.handleChange.bind(this);

}

handleChange(e) {

this.props.action(this.props.id, e.target.value);

}

render() {

return(

<input onChange={this.handleChange}></input>

);

}

}

Page 342: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

<NumberInputField id="1" action={this.multiply}/>

. . .

SD4x-3.5 342

class NumberInputField extends React.Component {

constructor(props) {

super(props);

this.handleChange = this.handleChange.bind(this);

}

handleChange(e) {

this.props.action(this.props.id, e.target.value);

}

render() {

return(

<input onChange={this.handleChange}></input>

);

}

}

Page 343: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

<NumberInputField id="1" action={this.multiply}/>

. . .

SD4x-3.5 343

class NumberInputField extends React.Component {

constructor(props) {

super(props);

this.handleChange = this.handleChange.bind(this);

}

handleChange(e) {

this.props.action(this.props.id, e.target.value);

}

render() {

return(

<input onChange={this.handleChange}></input>

);

}

}

Page 344: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

<NumberInputField id="1" action={this.multiply}/>

. . .

SD4x-3.5 344

class NumberInputField extends React.Component {

constructor(props) {

super(props);

this.handleChange = this.handleChange.bind(this);

}

handleChange(e) {

this.props.action(this.props.id, e.target.value);

}

render() {

return(

<input onChange={this.handleChange}></input>

);

}

}

Page 345: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

<NumberInputField id="1" action={this.multiply}/>

. . .

SD4x-3.5 345

class NumberInputField extends React.Component {

constructor(props) {

super(props);

this.handleChange = this.handleChange.bind(this);

}

handleChange(e) {

this.props.action(this.props.id, e.target.value);

}

render() {

return(

<input onChange={this.handleChange}></input>

);

}

}

Page 346: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

<NumberInputField id="1" action={this.multiply}/>

. . .

SD4x-3.5 346

class NumberInputField extends React.Component {

constructor(props) {

super(props);

this.handleChange = this.handleChange.bind(this);

}

handleChange(e) {

this.props.action(this.props.id, e.target.value);

}

render() {

return(

<input onChange={this.handleChange}></input>

);

}

}

Page 347: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

<NumberInputField id="1" action={this.multiply}/>

. . .

SD4x-3.5 347

class NumberInputField extends React.Component {

constructor(props) {

super(props);

this.handleChange = this.handleChange.bind(this);

}

handleChange(e) {

this.props.action(this.props.id, e.target.value);

}

render() {

return(

<input onChange={this.handleChange}></input>

);

}

}

Page 348: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

<NumberInputField id="1" action={this.multiply}/>

. . .

SD4x-3.5 348

class NumberInputField extends React.Component {

constructor(props) {

super(props);

this.handleChange = this.handleChange.bind(this);

}

handleChange(e) {

this.props.action(this.props.id, e.target.value);

}

render() {

return(

<input onChange={this.handleChange}></input>

);

}

}

Page 349: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

<NumberInputField id="1" action={this.multiply}/>

. . .

SD4x-3.5 349

class NumberInputField extends React.Component {

constructor(props) {

super(props);

this.handleChange = this.handleChange.bind(this);

}

handleChange(e) {

this.props.action(this.props.id, e.target.value);

}

render() {

return(

<input onChange={this.handleChange}></input>

);

}

}

Page 350: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

<NumberInputField id="1" action={this.multiply}/>

. . .

SD4x-3.5 350

class NumberInputField extends React.Component {

constructor(props) {

super(props);

this.handleChange = this.handleChange.bind(this);

}

handleChange(e) {

this.props.action(this.props.id, e.target.value);

}

render() {

return(

<input onChange={this.handleChange}></input>

);

}

}

Page 351: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

<NumberInputField id="1" action={this.multiply}/>

. . .

SD4x-3.5 351

class NumberInputField extends React.Component {

constructor(props) {

super(props);

this.handleChange = this.handleChange.bind(this);

}

handleChange(e) {

this.props.action(this.props.id, e.target.value);

}

render() {

return(

<input onChange={this.handleChange}></input>

);

}

}

Page 352: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

<NumberInputField id="1" action={this.multiply}/>

. . .

SD4x-3.5 352

class NumberInputField extends React.Component {

constructor(props) {

super(props);

this.handleChange = this.handleChange.bind(this);

}

handleChange(e) {

this.props.action(this.props.id, e.target.value);

}

render() {

return(

<input onChange={this.handleChange}></input>

);

}

}

Page 353: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

<NumberInputField id="1" action={this.multiply}/>

. . .

SD4x-3.5 353

class NumberInputField extends React.Component {

constructor(props) {

super(props);

this.handleChange = this.handleChange.bind(this);

}

handleChange(e) {

this.props.action(this.props.id, e.target.value);

}

render() {

return(

<input onChange={this.handleChange}></input>

);

}

}

Page 354: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 354

Page 355: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 355

Page 356: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class Multiplier extends React.Component {

. . .

multiply(id, val) {

if (id == 1) {

this.setState( { input1: val,

product: val * this.state.input2 } );

}

else if (id == 2) {

this.setState( { input2: val,

product: this.state.input1 * val } );

}

}

. . .

SD4x-3.5 356

Page 357: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class OutputField extends React.Component {

render() {

return(

<div>The product is {this.props.product}.

</div>

);

}

}

ReactDOM.render(<Multiplier/>,

document.getElementById('container'));

class Multiplier extends React.Component {

. . .

<OutputField product={this.state.product}/>

. . .

SD4x-3.5 357

Page 358: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class OutputField extends React.Component {

render() {

return(

<div>The product is {this.props.product}.

</div>

);

}

}

ReactDOM.render(<Multiplier/>,

document.getElementById('container'));

class Multiplier extends React.Component {

. . .

<OutputField product={this.state.product}/>

. . .

SD4x-3.5 358

Page 359: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class OutputField extends React.Component {

render() {

return(

<div>The product is {this.props.product}.

</div>

);

}

}

ReactDOM.render(<Multiplier/>,

document.getElementById('container'));

class Multiplier extends React.Component {

. . .

<OutputField product={this.state.product}/>

. . .

SD4x-3.5 359

Page 360: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class OutputField extends React.Component {

render() {

return(

<div>The product is {this.props.product}.

</div>

);

}

}

ReactDOM.render(<Multiplier/>,

document.getElementById('container'));

class Multiplier extends React.Component {

. . .

<OutputField product={this.state.product}/>

. . .

SD4x-3.5 360

Page 361: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class OutputField extends React.Component {

render() {

return(

<div>The product is {this.props.product}.

</div>

);

}

}

ReactDOM.render(<Multiplier/>,

document.getElementById('container'));

class Multiplier extends React.Component {

. . .

<OutputField product={this.state.product}/>

. . .

SD4x-3.5 361

Page 362: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class OutputField extends React.Component {

render() {

return(

<div>The product is {this.props.product}.

</div>

);

}

}

ReactDOM.render(<Multiplier/>,

document.getElementById('container'));

class Multiplier extends React.Component {

. . .

<OutputField product={this.state.product}/>

. . .

SD4x-3.5 362

Page 363: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class OutputField extends React.Component {

render() {

return(

<div>The product is {this.props.product}.

</div>

);

}

}

ReactDOM.render(<Multiplier/>,

document.getElementById('container'));

class Multiplier extends React.Component {

. . .

<OutputField product={this.state.product}/>

. . .

SD4x-3.5 363

Page 364: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class OutputField extends React.Component {

render() {

return(

<div>The product is {this.props.product}.

</div>

);

}

}

ReactDOM.render(<Multiplier/>,

document.getElementById('container'));

class Multiplier extends React.Component {

. . .

<OutputField product={this.state.product}/>

. . .

SD4x-3.5 364

Page 365: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Review

• React allows us to create reusable, modularized components that can be combined to form web applications

• Components can communicate with each other via callback methods that are set as props

SD4x-3.5 365

Page 366: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Video 3.6

React and APIs

Chris Murphy

SD4x-3.6 366

Page 367: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Review

• React allows us to create modular JavaScript components that we can use in our HTML pages to develop web applications

• How can we take advantage of the modular nature of the Web?

SD4x-3.6 367

Page 368: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Web development in the old days

SD4x-3.6 368

Page 369: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Designing software for the Web

• How can we make this better?

• Use design paradigms with the following goals:

• Break up code into distinct components

• The components interact with each other in a “standard” manner

• Makes it easy to change any component

• Less dependency and coupling

SD4x-3.6 369

Page 370: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Service-Oriented Architecture

• Letter by Jeff Bezos to all employees at Amazon (circa 2002)

• “All teams will henceforth expose their data and functionality through service interfaces.”

• “The only communication allowed is via service interface calls over the network.”

• “All service interfaces, without exception, must be designed from the ground up to be externalizable. That is to say, the team must plan and design to be able to expose the interface to developers in the outside world. No exceptions.”

SD4x-3.6 370

Page 371: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Software as a Service (SaaS)

• Extends the idea of Service-oriented Architecture

• SaaS – entire software runs as a service

• Examples

• Google Docs (as opposed to Microsoft Word)

• Gmail (as opposed to email clients like Outlook)

• Cloud9 (as opposed to Eclipse)

SD4x-3.6 371

Page 372: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Software as a Service: Advantages

• No user installation is needed

• Less likely to lose data

• Users can collaborate with each other

• Upgrading software and datasets is easy

• Software is centralized in a single environment (don’t need to worry about versions of operating systems, etc.)

• User’s computer (hardware and software specifications) don’t matter – usually all that’s needed is a web browser

SD4x-3.6 372

Page 373: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Microservices

SD4x-3.6 373

Page 374: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Microservices

SD4x-3.6 374

Page 375: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

REST

• How do well-designed web servers behave?

• Define a set of rules and conventions

• REST: REpresentational State Transfer

• Collection of resources on which specific operations can be performed

• URI names resources, not pages or actions

• Self-contained - which resource, what to do with it, server doesn’t need to maintain state between requests

SD4x-3.6 375

Page 376: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

What is an API?

• An API is an Application Programming Interface

• In web programming, an API is a URL or a set of URLs that returns pure data to requests

• APIs can be used to incorporate data and functionality from other sources in your webapp

SD4x-3.6 376

Page 377: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

The New York Times

• The New York Times is an American daily newspaper company

• The New York Times provides a variety of APIs that provide article data, books data, movies data, and more

• You can see more about available APIs and request access at https://developer.nytimes.com/

SD4x-3.6 377

Page 378: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Our Goal

• Created a webapp that creates a dashboard of clickable New York Times article images

SD4x-3.6 378

Page 379: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

• Request a developer key for the Article Search API at https://developer.nytimes.com/

• You can test out the API and what the returned data looks like at https://developer.nytimes.com/article_search_v2.json

SD4x-3.6 379

Page 380: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Structure

• First, let’s create a new React component named ArticlesGrid to store the data in the page

class ArticlesGrid extends React.Component {

constructor (props) {

super(props);

this.state = {

articles: []

};

}

. . .

SD4x-3.6 380

Page 381: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Structure

• First, let’s create a new React component named ArticlesGrid to store the data in the page

class ArticlesGrid extends React.Component {

constructor (props) {

super(props);

this.state = {

articles: []

};

}

. . .

SD4x-3.6 381

Page 382: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Structure

• First, let’s create a new React component named ArticlesGrid to store the data in the page

class ArticlesGrid extends React.Component {

constructor (props) {

super(props);

this.state = {

articles: []

};

}

. . .

SD4x-3.6 382

Page 383: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Structure

• First, let’s create a new React component named ArticlesGrid to store the data in the page

class ArticlesGrid extends React.Component {

constructor (props) {

super(props);

this.state = {

articles: []

};

}

. . .

SD4x-3.6 383

Page 384: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Data

• Let’s start by getting some data from the API with a search term.

• We will do this with jQuery AJAXclass ArticlesGrid extends React.Component {

. . .

componentDidMount () {

var url=

'http://api.nytimes.com/svc/search/v2/articlesearch.json?'

+ 'api-key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$.getJSON(url, function(data, status) {

return this.setState({articles: this.parse(data)});

}.bind(this));

}

. . .

SD4x-3.6 384

Page 385: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Data

• Let’s start by getting some data from the API with a search term.

• We will do this with jQuery AJAXclass ArticlesGrid extends React.Component {

. . .

componentDidMount () {

var url=

'http://api.nytimes.com/svc/search/v2/articlesearch.json?'

+ 'api-key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$.getJSON(url, function(data, status) {

return this.setState({articles: this.parse(data)});

}.bind(this));

}

. . .

SD4x-3.6 385

Page 386: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Data

• Let’s start by getting some data from the API with a search term.

• We will do this with jQuery AJAXclass ArticlesGrid extends React.Component {

. . .

componentDidMount () {

var url=

'http://api.nytimes.com/svc/search/v2/articlesearch.json?'

+ 'api-key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$.getJSON(url, function(data, status) {

return this.setState({articles: this.parse(data)});

}.bind(this));

}

. . .

SD4x-3.6 386

Page 387: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Data

• Let’s start by getting some data from the API with a search term.

• We will do this with jQuery AJAX

SD4x-3.6 387

class ArticlesGrid extends React.Component {

. . .

componentDidMount () {

var url=

'http://api.nytimes.com/svc/search/v2/articlesearch.json?'

+ 'api-key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$.getJSON(url, function(data, status) {

return this.setState({articles: this.parse(data)});

}.bind(this));

}

. . .

Page 388: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Data

• Let’s start by getting some data from the API with a search term.

• We will do this with jQuery AJAXclass ArticlesGrid extends React.Component {

. . .

componentDidMount () {

var url=

'http://api.nytimes.com/svc/search/v2/articlesearch.json?'

+ 'api-key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$.getJSON(url, function(data, status) {

return this.setState({articles: this.parse(data)});

}.bind(this));

}

. . .

SD4x-3.6 388

Page 389: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Data

• Let’s start by getting some data from the API with a search term.

• We will do this with jQuery AJAXclass ArticlesGrid extends React.Component {

. . .

componentDidMount () {

var url=

'http://api.nytimes.com/svc/search/v2/articlesearch.json?'

+ 'api-key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$.getJSON(url, function(data, status) {

return this.setState({articles: this.parse(data)});

}.bind(this));

}

. . .

SD4x-3.6 389

Page 390: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Data

• Let’s start by getting some data from the API with a search term.

• We will do this with jQuery AJAX

SD4x-3.6 390

class ArticlesGrid extends React.Component {

. . .

componentDidMount () {

var url=

'http://api.nytimes.com/svc/search/v2/articlesearch.json?'

+ 'api-key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$.getJSON(url, function(data, status) {

return this.setState({articles: this.parse(data)});

}.bind(this));

}

. . .

Page 391: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Data

• Let’s start by getting some data from the API with a search term.

• We will do this with jQuery AJAX

SD4x-3.6 391

class ArticlesGrid extends React.Component {

. . .

componentDidMount () {

var url=

'http://api.nytimes.com/svc/search/v2/articlesearch.json?'

+ 'api-key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$.getJSON(url, function(data, status) {

return this.setState({articles: this.parse(data)});

}.bind(this));

}

. . .

Page 392: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Data

• Let’s start by getting some data from the API with a search term.

• We will do this with jQuery AJAXclass ArticlesGrid extends React.Component {

. . .

componentDidMount () {

var url=

'http://api.nytimes.com/svc/search/v2/articlesearch.json?'

+ 'api-key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$.getJSON(url, function(data, status) {

return this.setState({articles: this.parse(data)});

}.bind(this));

}

. . .

SD4x-3.6 392

Page 393: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Data

• Let’s start by getting some data from the API with a search term.

• We will do this with jQuery AJAXclass ArticlesGrid extends React.Component {

. . .

componentDidMount () {

var url=

'http://api.nytimes.com/svc/search/v2/articlesearch.json?'

+ 'api-key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$.getJSON(url, function(data, status) {

return this.setState({articles: this.parse(data)});

}.bind(this));

}

. . .

SD4x-3.6 393

Page 394: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Data

• Let’s start by getting some data from the API with a search term.

• We will do this with jQuery AJAXclass ArticlesGrid extends React.Component {

. . .

componentDidMount () {

var url=

'http://api.nytimes.com/svc/search/v2/articlesearch.json?'

+ 'api-key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$.getJSON(url, function(data, status) {

return this.setState({articles: this.parse(data)});

}.bind(this));

}

. . .

SD4x-3.6 394

Page 395: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Data

• Let’s start by getting some data from the API with a search term.

• We will do this with jQuery AJAXclass ArticlesGrid extends React.Component {

. . .

componentDidMount () {

var url=

'http://api.nytimes.com/svc/search/v2/articlesearch.json?'

+ 'api-key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$.getJSON(url, function(data, status) {

return this.setState({articles: this.parse(data)});

}.bind(this));

}

. . .

SD4x-3.6 395

Page 396: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.6 396

{

"response": {

"meta": {

"hits": 4251,

"time": 36,

"offset": 0

},

"docs": [

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": "Having invited Senator LA FOLLETTE to make a

statement of his cause and case in today's TIMES, we would

refer to it only with becoming courtesy. Its great lack must

be obvious to every reader. This is its extreme indefiniteness.

The Senator uses w...",

"lead_paragraph": "Having invited Senator LA FOLLETTE

to make a statement of his cause and case in today's TIMES,

we would refer to it only with becoming courtesy. Its great

lack must be obvious to every reader. This is its extreme

indefiniteness. The Senator uses with vehemence a great many

terms without defining one of them.",

. . .

}

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": ”At Washington last week the spokesman...

Page 397: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.6 397

{

"response": {

"meta": {

"hits": 4251,

"time": 36,

"offset": 0

},

"docs": [

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": "Having invited Senator LA FOLLETTE to make a

statement of his cause and case in today's TIMES, we would

refer to it only with becoming courtesy. Its great lack must

be obvious to every reader. This is its extreme indefiniteness.

The Senator uses w...",

"lead_paragraph": "Having invited Senator LA FOLLETTE

to make a statement of his cause and case in today's TIMES,

we would refer to it only with becoming courtesy. Its great

lack must be obvious to every reader. This is its extreme

indefiniteness. The Senator uses with vehemence a great many

terms without defining one of them.",

. . .

}

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": ”At Washington last week the spokesman...

Page 398: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.6 398

{

"response": {

"meta": {

"hits": 4251,

"time": 36,

"offset": 0

},

"docs": [

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": "Having invited Senator LA FOLLETTE to make a

statement of his cause and case in today's TIMES, we would

refer to it only with becoming courtesy. Its great lack must

be obvious to every reader. This is its extreme indefiniteness.

The Senator uses w...",

"lead_paragraph": "Having invited Senator LA FOLLETTE

to make a statement of his cause and case in today's TIMES,

we would refer to it only with becoming courtesy. Its great

lack must be obvious to every reader. This is its extreme

indefiniteness. The Senator uses with vehemence a great many

terms without defining one of them.",

. . .

}

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": ”At Washington last week the spokesman...

Page 399: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.6 399

{

"response": {

"meta": {

"hits": 4251,

"time": 36,

"offset": 0

},

"docs": [

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": "Having invited Senator LA FOLLETTE to make a

statement of his cause and case in today's TIMES, we would

refer to it only with becoming courtesy. Its great lack must

be obvious to every reader. This is its extreme indefiniteness.

The Senator uses w...",

"lead_paragraph": "Having invited Senator LA FOLLETTE

to make a statement of his cause and case in today's TIMES,

we would refer to it only with becoming courtesy. Its great

lack must be obvious to every reader. This is its extreme

indefiniteness. The Senator uses with vehemence a great many

terms without defining one of them.",

. . .

}

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": ”At Washington last week the spokesman...

Page 400: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.6 400

{

"response": {

"meta": {

"hits": 4251,

"time": 36,

"offset": 0

},

"docs": [

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": "Having invited Senator LA FOLLETTE to make a

statement of his cause and case in today's TIMES, we would

refer to it only with becoming courtesy. Its great lack must

be obvious to every reader. This is its extreme indefiniteness.

The Senator uses w...",

"lead_paragraph": "Having invited Senator LA FOLLETTE

to make a statement of his cause and case in today's TIMES,

we would refer to it only with becoming courtesy. Its great

lack must be obvious to every reader. This is its extreme

indefiniteness. The Senator uses with vehemence a great many

terms without defining one of them.",

. . .

}

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": ”At Washington last week the spokesman...

Page 401: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.6 401

{

"response": {

"meta": {

"hits": 4251,

"time": 36,

"offset": 0

},

"docs": [

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": "Having invited Senator LA FOLLETTE to make a

statement of his cause and case in today's TIMES, we would

refer to it only with becoming courtesy. Its great lack must

be obvious to every reader. This is its extreme indefiniteness.

The Senator uses w...",

"lead_paragraph": "Having invited Senator LA FOLLETTE

to make a statement of his cause and case in today's TIMES,

we would refer to it only with becoming courtesy. Its great

lack must be obvious to every reader. This is its extreme

indefiniteness. The Senator uses with vehemence a great many

terms without defining one of them.",

. . .

}

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": ”At Washington last week the spokesman...

Page 402: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.6 402

{

"response": {

"meta": {

"hits": 4251,

"time": 36,

"offset": 0

},

"docs": [

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": "Having invited Senator LA FOLLETTE to make a

statement of his cause and case in today's TIMES, we would

refer to it only with becoming courtesy. Its great lack must

be obvious to every reader. This is its extreme indefiniteness.

The Senator uses w...",

"lead_paragraph": "Having invited Senator LA FOLLETTE

to make a statement of his cause and case in today's TIMES,

we would refer to it only with becoming courtesy. Its great

lack must be obvious to every reader. This is its extreme

indefiniteness. The Senator uses with vehemence a great many

terms without defining one of them.",

. . .

}

{

"web_url": "https://query.nytimes.com/gst/...",

"snippet": ”At Washington last week the spokesman...

Page 403: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Parsing Data

• The NY Times API will return a lot of raw data!

• Let’s parse the data into something we can use

• For each article, we’ll keep the image URL, title, and URL to original article if a large image exists

SD4x-3.6 403

Page 404: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 404

Page 405: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 405

Page 406: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 406

Page 407: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 407

Page 408: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 408

Page 409: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 409

Page 410: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 410

Page 411: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 411

Page 412: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 412

Page 413: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 413

Page 414: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 414

Page 415: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 415

Page 416: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 416

Page 417: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 417

Page 418: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

class ArticlesGrid extends React.Component {

. . .

parse(results) {

if( !results || !results.response ) return [];

var articles = results.response.docs;

var parsedArticles = [];

for (var i = 0; i < articles.length; i++) {

var article = articles[i];

if (article.multimedia.find(this.isXL)) {

parsedArticles.push({

id: article._id,

title: article.headline.main || 'Untitled',

imageURL: article.multimedia.find(this.isXL).url || '#',

webURL: article.web_url || '#'

});

}

}

return parsedArticles;

}

isXL (image) {

return image.subtype === 'xlarge';

}

SD4x-3.6 418

Page 419: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 419

Page 420: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 420

Page 421: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 421

Page 422: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 422

Page 423: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 423

Page 424: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 424

Page 425: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 425

Page 426: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 426

Page 427: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 427

Page 428: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 428

Page 429: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 429

Page 430: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 430

Page 431: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 431

Page 432: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Now that we have the data, let’s make a component to display each article!

• This is shorthand for a component that only has a “render” function

var Article = function({article}) {

var imgURL = 'https://static01.nyt.com/' + article.imageURL;

return (

<div className='article'>

<a className='article-link' href={article.webURL}>

<img className='article-image'

title={article.title}

src={imgURL} />

</a>

</div>

);

}

SD4x-3.6 432

Page 433: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Finally, we can render the Articles Grid to tie it all together.

class ArticlesGrid extends React.Component {

. . .

render () {

return this.state.articles && (

<div className='articles'>

{ this.state.articles.map( function (article) {

return <Article article={article} key={article._id} />;

})}

</div>

);

}

SD4x-3.6 433

Page 434: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Finally, we can render the Articles Grid to tie it all together.

class ArticlesGrid extends React.Component {

. . .

render () {

return this.state.articles && (

<div className='articles'>

{ this.state.articles.map( function (article) {

return <Article article={article} key={article._id} />;

})}

</div>

);

}

SD4x-3.6 434

Page 435: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Finally, we can render the Articles Grid to tie it all together.

class ArticlesGrid extends React.Component {

. . .

render () {

return this.state.articles && (

<div className='articles'>

{ this.state.articles.map( function (article) {

return <Article article={article} key={article._id} />;

})}

</div>

);

}

SD4x-3.6 435

Page 436: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Finally, we can render the Articles Grid to tie it all together.

class ArticlesGrid extends React.Component {

. . .

render () {

return this.state.articles && (

<div className='articles'>

{ this.state.articles.map( function (article) {

return <Article article={article} key={article._id} />;

})}

</div>

);

}

SD4x-3.6 436

Page 437: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Finally, we can render the Articles Grid to tie it all together.

class ArticlesGrid extends React.Component {

. . .

render () {

return this.state.articles && (

<div className='articles'>

{ this.state.articles.map( function (article) {

return <Article article={article} key={article._id} />;

})}

</div>

);

}

SD4x-3.6 437

Page 438: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Finally, we can render the Articles Grid to tie it all together.

class ArticlesGrid extends React.Component {

. . .

render () {

return this.state.articles && (

<div className='articles'>

{ this.state.articles.map( function (article) {

return <Article article={article} key={article._id} />;

})}

</div>

);

}

SD4x-3.6 438

Page 439: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Finally, we can render the Articles Grid to tie it all together.

class ArticlesGrid extends React.Component {

. . .

render () {

return this.state.articles && (

<div className='articles'>

{ this.state.articles.map( function (article) {

return <Article article={article} key={article._id} />;

})}

</div>

);

}

SD4x-3.6 439

Page 440: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Finally, we can render the Articles Grid to tie it all together.

class ArticlesGrid extends React.Component {

. . .

render () {

return this.state.articles && (

<div className='articles'>

{ this.state.articles.map( function (article) {

return <Article article={article} key={article._id} />;

})}

</div>

);

}

SD4x-3.6 440

Page 441: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Finally, we can render the Articles Grid to tie it all together.

class ArticlesGrid extends React.Component {

. . .

render () {

return this.state.articles && (

<div className='articles'>

{ this.state.articles.map( function (article) {

return <Article article={article} key={article._id} />;

})}

</div>

);

}

SD4x-3.6 441

Page 442: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Finally, we can render the Articles Grid to tie it all together.

class ArticlesGrid extends React.Component {

. . .

render () {

return this.state.articles && (

<div className='articles'>

{ this.state.articles.map( function (article) {

return <Article article={article} key={article._id} />;

})}

</div>

);

}

SD4x-3.6 442

Page 443: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Displaying Data

• Finally, we can render the Articles Grid to tie it all together.

class ArticlesGrid extends React.Component {

. . .

render () {

return this.state.articles && (

<div className='articles'>

{ this.state.articles.map( function (article) {

return <Article article={article} key={article._id} />;

})}

</div>

);

}

SD4x-3.6 443

Page 444: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Summary

• Service Oriented Architecture and Software as a Service (SaaS) simplify the creation of web applications by allowing for combinations of online components

• We can accesses services via RESTful APIs and develop React components to make use of them

SD4x-3.6 444

Page 445: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Video 3.7

React App Development

Chris Murphy

SD4x-3.7 445

Page 446: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Review

• React allows us to create web applications by developing reusable, modular components

• So far, we’ve seen how to define components within the HTML pages

• How do we develop larger applications with multiple components?

SD4x-3.7 446

Page 447: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Node.js - Introduction

• Node.js is a free, open source platform and framework built in JavaScript

• Includes suite of tools that allows user to prepare JavaScript (and thus React) applications for deployment

• Utilizes Node.js Package Manager (npm) to install programs and manage dependencies

SD4x-3.7 447

Page 448: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Node.js - Benefits

• Instead of including all JavaScript code in a <script> tag, now we can separate the components into different files to make code more modular

• Node.js allows us to incorporate dependencies of the code within the current file

var React = require('react');

var ReactDOM = require('react-dom');

import MyComponent from './MyComponent.js';

SD4x-3.7 448

Page 449: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Node.js - Benefits

• Instead of including all JavaScript code in a <script> tag, now we can separate the components into different files to make code more modular

• Node.js allows us to incorporate dependencies of the code within the current file

var React = require('react');

var ReactDOM = require('react-dom');

import MyComponent from './MyComponent.js';

SD4x-3.7 449

Page 450: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Node.js - Benefits

• Instead of including all JavaScript code in a <script> tag, now we can separate the components into different files to make code more modular

• Node.js allows us to incorporate dependencies of the code within the current file

var React = require('react');

var ReactDOM = require('react-dom');

import MyComponent from './MyComponent.js';

SD4x-3.7 450

Page 451: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Node.js - Installation

• Navigate to https://nodejs.org/en/download/ and download and install Node.js and appropriate packages

• Although npm always comes with a Node.jsinstallation, be sure to update the version to the most recent with the following command.

npm install npm -g

SD4x-3.7 451

Page 452: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating a React App - Considerations

• Including dependencies (React, React-DOM libraries, etc.)

• Making code compatible with browsers that only support older versions of JavaScript

• Transforming JSX into JavaScript

• Modularity: implementing modules in separate files, bundling them as dependencies

SD4x-3.7 452

Page 453: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating a React App with Node.js - Setup

• Fortunately, there exists a package (through npm) that takes all of the above into consideration when creating a React app

• Incorporates Babel for JSX and ES6 transformation

• Incorporates Webpack for bundling

SD4x-3.7 453

npm install -g create-react-app

Page 454: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Creating a React App with Node.js - Setup

• Fortunately, there exists a package (through npm) that takes all of the above into consideration when creating a React app

• Incorporates Babel for JSX and ES6 transformation

• Incorporates Webpack for bundling

• To create new React app, run the following command in the desired parent directory of new application

create-react-app my-app

SD4x-3.7 454

npm install -g create-react-app

Page 455: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React App

SD4x-3.7 455

• package.json: information about app, lists of dependencies, shortcuts for scripts

• public: directory containing HTML files, images, other static web content

• src: directory containing JavaScript and CSS files

Page 456: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Starting React App with Node.js

• You can start the default app as follows:

cd my-app/

npm start

SD4x-3.7 456

Page 457: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Starting React App with Node.js

• You can start the default app as follows:

• This will start a web server that listens for incoming HTTP requests on port 3000 on your computer

cd my-app/

npm start

SD4x-3.7 457

Page 458: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Starting React App with Node.js

• You can start the default app as follows:

• This will start a web server that listens for incoming HTTP requests on port 3000 on your computer

• You can access the web server by accessing http://localhost:3000/ from your computer

cd my-app/

npm start

SD4x-3.7 458

Page 459: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 459

Page 460: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Incorporating Components

• We can now create separate JavaScript files for each component.

• src/Counter.js would look like this:

var React = require('react');

class Counter extends React.Component {

constructor(props) { . . . }

incrementCount() { . . . }

render() { . . . }

};

export default Counter;

SD4x-3.7 460

Page 461: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Incorporating Components

• We can now create separate JavaScript files for each component.

• src/Counter.js would look like this:

var React = require('react');

class Counter extends React.Component {

constructor(props) { . . . }

incrementCount() { . . . }

render() { . . . }

};

export default Counter;

SD4x-3.7 461

Page 462: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Incorporating Components

• We can now create separate JavaScript files for each component.

• src/Counter.js would look like this:

var React = require('react');

class Counter extends React.Component {

constructor(props) { . . . }

incrementCount() { . . . }

render() { . . . }

};

export default Counter;

SD4x-3.7 462

Page 463: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Incorporating Components

• We can now create separate JavaScript files for each component.

• src/Counter.js would look like this:

var React = require('react');

class Counter extends React.Component {

constructor(props) { . . . }

incrementCount() { . . . }

render() { . . . }

};

export default Counter;

SD4x-3.7 463

Page 464: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Incorporating Components into the App

• Edit src/App.js as follows:

import Counter from './Counter.js';

SD4x-3.7 464

class App extends Component {

render() {

return (

<div className="App">

<Counter />

</div>

);

}

}

Page 465: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Incorporating Components into the App

• Edit src/App.js as follows:

import Counter from './Counter.js';

SD4x-3.7 465

class App extends Component {

render() {

return (

<div className="App">

<Counter />

</div>

);

}

}

Page 466: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Incorporating Components into the App

• Edit src/App.js as follows:

import Counter from './Counter.js';

SD4x-3.7 466

class App extends Component {

render() {

return (

<div className="App">

<Counter />

</div>

);

}

}

Page 467: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 467

Page 468: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 468

Page 469: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 469

Page 470: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 470

Page 471: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 471

Page 472: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 472

Page 473: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 473

Page 474: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 474

App

Page 475: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 475

AppDogs

Page 476: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 476

AppDogsDogItem

DogItem

Page 477: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 477

AppDogsDogItem

DogItem

AddDog

Page 478: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

import React, { Component } from 'react';

import Dogs from './components/Dogs';

import AddDog from './components/AddDog';

import './App.css';

class App extends Component {

constructor() { . . . }

handleAddDog(dog) { . . . }

handleDeleteDog(name) { . . . }

render() {

return (

<div className="App">

<Dogs dogs={this.state.dogs}

onDelete={this.handleDeleteDog.bind(this)} />

<AddDog onAddDog={this.handleAddDog.bind(this)} />

<hr />

</div>

);

}

};

SD4x-3.7 478

Page 479: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

import React, { Component } from 'react';

import Dogs from './components/Dogs';

import AddDog from './components/AddDog';

import './App.css';

class App extends Component {

constructor() { . . . }

handleAddDog(dog) { . . . }

handleDeleteDog(name) { . . . }

render() {

return (

<div className="App">

<Dogs dogs={this.state.dogs}

onDelete={this.handleDeleteDog.bind(this)} />

<AddDog onAddDog={this.handleAddDog.bind(this)} />

<hr />

</div>

);

}

};

SD4x-3.7 479

Page 480: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

import React, { Component } from 'react';

import Dogs from './components/Dogs';

import AddDog from './components/AddDog';

import './App.css';

class App extends Component {

constructor() { . . . }

handleAddDog(dog) { . . . }

handleDeleteDog(name) { . . . }

render() {

return (

<div className="App">

<Dogs dogs={this.state.dogs}

onDelete={this.handleDeleteDog.bind(this)} />

<AddDog onAddDog={this.handleAddDog.bind(this)} />

<hr />

</div>

);

}

};

SD4x-3.7 480

Page 481: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

import React, { Component } from 'react';

import Dogs from './components/Dogs';

import AddDog from './components/AddDog';

import './App.css';

class App extends Component {

constructor() { . . . }

handleAddDog(dog) { . . . }

handleDeleteDog(name) { . . . }

render() {

return (

<div className="App">

<Dogs dogs={this.state.dogs}

onDelete={this.handleDeleteDog.bind(this)} />

<AddDog onAddDog={this.handleAddDog.bind(this)} />

<hr />

</div>

);

}

};

SD4x-3.7 481

Page 482: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

import React, { Component } from 'react';

import Dogs from './components/Dogs';

import AddDog from './components/AddDog';

import './App.css';

class App extends Component {

constructor() { . . . }

handleAddDog(dog) { . . . }

handleDeleteDog(name) { . . . }

render() {

return (

<div className="App">

<Dogs dogs={this.state.dogs}

onDelete={this.handleDeleteDog.bind(this)} />

<AddDog onAddDog={this.handleAddDog.bind(this)} />

<hr />

</div>

);

}

};

SD4x-3.7 482

Page 483: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

import React, { Component } from 'react';

import Dogs from './components/Dogs';

import AddDog from './components/AddDog';

import './App.css';

class App extends Component {

constructor() { . . . }

handleAddDog(dog) { . . . }

handleDeleteDog(name) { . . . }

render() {

return (

<div className="App">

<Dogs dogs={this.state.dogs}

onDelete={this.handleDeleteDog.bind(this)} />

<AddDog onAddDog={this.handleAddDog.bind(this)} />

<hr />

</div>

);

}

};

SD4x-3.7 483

Page 484: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

import React, { Component } from 'react';

import Dogs from './components/Dogs';

import AddDog from './components/AddDog';

import './App.css';

class App extends Component {

constructor() { . . . }

handleAddDog(dog) { . . . }

handleDeleteDog(name) { . . . }

render() {

return (

<div className="App">

<Dogs dogs={this.state.dogs}

onDelete={this.handleDeleteDog.bind(this)} />

<AddDog onAddDog={this.handleAddDog.bind(this)} />

<hr />

</div>

);

}

};

SD4x-3.7 484

Page 485: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

import React, { Component } from 'react';

import Dogs from './components/Dogs';

import AddDog from './components/AddDog';

import './App.css';

class App extends Component {

constructor() { . . . }

handleAddDog(dog) { . . . }

handleDeleteDog(name) { . . . }

render() {

return (

<div className="App">

<Dogs dogs={this.state.dogs}

onDelete={this.handleDeleteDog.bind(this)} />

<AddDog onAddDog={this.handleAddDog.bind(this)} />

<hr />

</div>

);

}

};

SD4x-3.7 485

Page 486: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

import React, { Component } from 'react';

import Dogs from './components/Dogs';

import AddDog from './components/AddDog';

import './App.css';

class App extends Component {

constructor() { . . . }

handleAddDog(dog) { . . . }

handleDeleteDog(name) { . . . }

render() {

return (

<div className="App">

<Dogs dogs={this.state.dogs}

onDelete={this.handleDeleteDog.bind(this)} />

<AddDog onAddDog={this.handleAddDog.bind(this)} />

<hr />

</div>

);

}

};

SD4x-3.7 486

Page 487: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

import React, { Component } from 'react';

import Dogs from './components/Dogs';

import AddDog from './components/AddDog';

import './App.css';

class App extends Component {

constructor() { . . . }

handleAddDog(dog) { . . . }

handleDeleteDog(name) { . . . }

render() {

return (

<div className="App">

<Dogs dogs={this.state.dogs}

onDelete={this.handleDeleteDog.bind(this)} />

<AddDog onAddDog={this.handleAddDog.bind(this)} />

<hr />

</div>

);

}

};

SD4x-3.7 487

Page 488: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

import React, { Component } from 'react';

import Dogs from './components/Dogs';

import AddDog from './components/AddDog';

import './App.css';

class App extends Component {

constructor() { . . . }

handleAddDog(dog) { . . . }

handleDeleteDog(name) { . . . }

render() {

return (

<div className="App">

<Dogs dogs={this.state.dogs}

onDelete={this.handleDeleteDog.bind(this)} />

<AddDog onAddDog={this.handleAddDog.bind(this)} />

<hr />

</div>

);

}

};

SD4x-3.7 488

Page 489: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 489

AppDogs

AddDog

Page 490: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

import React, { Component } from 'react';

import Dogs from './components/Dogs';

import AddDog from './components/AddDog';

import './App.css';

class App extends Component {

constructor() { . . . }

handleAddDog(dog) { . . . }

handleDeleteDog(name) { . . . }

render() {

return (

<div className="App">

<Dogs dogs={this.state.dogs}

onDelete={this.handleDeleteDog.bind(this)} />

<AddDog onAddDog={this.handleAddDog.bind(this)} />

<hr />

</div>

);

}

};

SD4x-3.7 490

Page 491: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

import React, { Component } from 'react';

import Dogs from './components/Dogs';

import AddDog from './components/AddDog';

import './App.css';

class App extends Component {

constructor() { . . . }

handleAddDog(dog) { . . . }

handleDeleteDog(name) { . . . }

render() {

return (

<div className="App">

<Dogs dogs={this.state.dogs}

onDelete={this.handleDeleteDog.bind(this)} />

<AddDog onAddDog={this.handleAddDog.bind(this)} />

<hr />

</div>

);

}

};

SD4x-3.7 491

Page 492: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing React Apps

• Mocha – widely used test runner (testing framework) used to run JavaScript tests

• Chai – assertion library for Behavior Driven Testing

• Enzyme – testing utility for React for manipulating and inspecting React Component state and output

SD4x-3.7 492

Page 493: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started - Installation

• To include Enzyme and Chai as dependencies, run the following command:

npm install --save-dev enzyme react-test-renderer chai

SD4x-3.7 493

Page 494: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started - Installation

• To include Enzyme and Chai as dependencies, run the following command:

• Note that the default file structure places all JavaScript and CSS code in the ‘src’ folder.

• We will create an additional folder within ‘src’ named ‘tests’ in which we include all testing scripts

• All test files must be in the form of *.test.js, e.g. Dogs.test.js

npm install --save-dev enzyme react-test-renderer chai

SD4x-3.7 494

Page 495: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

• Node.js should create a default App.test.js, or you can write your own

SD4x-3.7 495

Page 496: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

• Node.js should create a default App.test.js, or you can write your own

• Include libraries necessary for testing

• Import React and ReactDOM for component manipulation

• Import keywords from Enzyme

• Import keywords from Chai

import React from 'react';

import ReactDOM from 'react-dom';

import { mount, shallow } from 'enzyme';

import {expect} from 'chai';

SD4x-3.7 496

Page 497: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

• Node.js should create a default App.test.js, or you can write your own

• Include libraries necessary for testing

• Import React and ReactDOM for component manipulation

• Import keywords from Enzyme

• Import keywords from Chai

import React from 'react';

import ReactDOM from 'react-dom';

import { mount, shallow } from 'enzyme';

import {expect} from 'chai';

SD4x-3.7 497

Page 498: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

• Node.js should create a default App.test.js, or you can write your own

• Include libraries necessary for testing

• Import React and ReactDOM for component manipulation

• Import keywords from Enzyme

• Import keywords from Chai

import React from 'react';

import ReactDOM from 'react-dom';

import { mount, shallow } from 'enzyme';

import {expect} from 'chai';

SD4x-3.7 498

Page 499: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Getting Started

• Node.js should create a default App.test.js, or you can write your own

• Include libraries necessary for testing

• Import React and ReactDOM for component manipulation

• Import keywords from Enzyme

• Import keywords from Chai

import React from 'react';

import ReactDOM from 'react-dom';

import { mount, shallow } from 'enzyme';

import {expect} from 'chai';

SD4x-3.7 499

Page 500: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 500

Page 501: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 501

Page 502: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 502

Page 503: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 503

Page 504: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 504

Page 505: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 505

Page 506: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 506

Page 507: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 507

Page 508: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 508

Page 509: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 509

Page 510: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 510

Page 511: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 511

Page 512: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 512

Page 513: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 513

Page 514: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 514

Page 515: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 515

Page 516: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 516

Page 517: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Anatomy of a React Test

import React from 'react';

import { expect } from 'chai';

import { mount, shallow } from 'enzyme';

import App from '../App';

describe("Test suite for App component", function(){

it("only one element in App class", function() {

const wrapper = shallow(<App />);

expect(wrapper.find(".App")).length(1);

});

});

SD4x-3.7 517

Page 518: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing React Component Relationships

it('Dog List contains two dogs', function() {

const wrapper = mount(<App/>);

expect(wrapper.find('Dogs')

.find('DogItem')).length(2);

});

SD4x-3.7 518

Page 519: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing React Component Relationships

it('Dog List contains two dogs', function() {

const wrapper = mount(<App/>);

expect(wrapper.find('Dogs')

.find('DogItem')).length(2);

});

SD4x-3.7 519

Page 520: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing React Component Relationships

it('Dog List contains two dogs', function() {

const wrapper = mount(<App/>);

expect(wrapper.find('Dogs')

.find('DogItem')).length(2);

});

SD4x-3.7 520

Page 521: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing React Component Relationships

it('Dog List contains two dogs', function() {

const wrapper = mount(<App/>);

expect(wrapper.find('Dogs')

.find('DogItem')).length(2);

});

SD4x-3.7 521

Page 522: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing React Component Relationships

it('Dog List contains two dogs', function() {

const wrapper = mount(<App/>);

expect(wrapper.find('Dogs')

.find('DogItem')).length(2);

});

SD4x-3.7 522

Page 523: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing React Component Relationships

it('Dog List contains two dogs', function() {

const wrapper = mount(<App/>);

expect(wrapper.find('Dogs')

.find('DogItem')).length(2);

});

SD4x-3.7 523

Page 524: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing React Component Relationships

it('Dog List contains two dogs', function() {

const wrapper = mount(<App/>);

expect(wrapper.find('Dogs')

.find('DogItem')).length(2);

});

SD4x-3.7 524

Page 525: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 525

Page 526: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 526

Page 527: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 527

Page 528: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 528

Page 529: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 529

Page 530: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 530

Page 531: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 531

Page 532: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 532

Page 533: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 533

Page 534: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 534

Page 535: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 535

Page 536: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 536

Page 537: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 537

Page 538: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 538

Page 539: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 539

Page 540: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 540

Page 541: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 541

Page 542: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 542

Page 543: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Data Entry and Form Submission

it("successfully adds dog to list when form submitted",

function() {

const wrapper = mount(<App/>);

const adddog = wrapper.find('AddDog');

adddog.find('#dogName').get(0).value = 'Lola';

adddog.find('#imageURL').get(0).value = 'https://

static.pexels.com/photos/54386/pexels-

photo-54386.jpeg';

adddog.find('#dogBreed').get(0).value = 'Beagle';

const form = adddog.find('form');

form.simulate('submit');

expect(wrapper.find('Dogs')

.find('DogItem')).length(3);

expect(wrapper.state().dogs[2].name == 'Lola');

});

SD4x-3.7 543

Page 544: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Links

it('removes dog from list when deleted', function() {

const wrapper = mount(<App/>);

const deleteLink = wrapper.find('a').first();

deleteLink.simulate('click');

expect(wrapper.find('Dogs')

.find('DogItem')).length(1);

});

SD4x-3.7 544

Page 545: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Links

it('removes dog from list when deleted', function() {

const wrapper = mount(<App/>);

const deleteLink = wrapper.find('a').first();

deleteLink.simulate('click');

expect(wrapper.find('Dogs')

.find('DogItem')).length(1);

});

SD4x-3.7 545

Page 546: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Links

it('removes dog from list when deleted', function() {

const wrapper = mount(<App/>);

const deleteLink = wrapper.find('a').first();

deleteLink.simulate('click');

expect(wrapper.find('Dogs')

.find('DogItem')).length(1);

});

SD4x-3.7 546

Page 547: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Links

it('removes dog from list when deleted', function() {

const wrapper = mount(<App/>);

const deleteLink = wrapper.find('a').first();

deleteLink.simulate('click');

expect(wrapper.find('Dogs')

.find('DogItem')).length(1);

});

SD4x-3.7 547

Page 548: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Links

it('removes dog from list when deleted', function() {

const wrapper = mount(<App/>);

const deleteLink = wrapper.find('a').first();

deleteLink.simulate('click');

expect(wrapper.find('Dogs')

.find('DogItem')).length(1);

});

SD4x-3.7 548

Page 549: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Testing Links

it('removes dog from list when deleted', function() {

const wrapper = mount(<App/>);

const deleteLink = wrapper.find('a').first();

deleteLink.simulate('click');

expect(wrapper.find('Dogs')

.find('DogItem')).length(1);

});

SD4x-3.7 549

Page 550: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Running Tests

• To run tests, navigate to the project within the terminal and run the following command:

npm run test

SD4x-3.7 550

Page 551: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.7 551

Page 552: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Running Tests: Success!

SD4x-3.7 552

Page 553: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Summary

• We can use Node.js to create React applications

• This allows us to put component code into separate .js files and then include them into our App as necessary

• Mocha, Chai, and Enzyme can be used for testing our React apps

SD4x-3.7 553

Page 554: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Video 3.8

ES6

Chris Murphy

SD4x-3.8 554

Page 555: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

What is ES6?

• ES6 stands for ECMAScript 6

• ECMAScript is the ”proper” name for JavaScript

• ES6 is the newest JavaScript Specification, released in 2015

SD4x-3.8 555

Page 556: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

What can you do with ES6?

• In ES6, you can…

• Define constants

• Use simpler notations for function declarations

• Build classes

• Refactor code into modules

• Store data in Sets, Maps, and Typed Arrays

• Copy objects in one line of code

• … and much more!

SD4x-3.8 556

Page 557: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Arrow Functions

• New syntax for defining functions using arrows

• ES5 Syntax:var arr = [1,2,3,4,5];

var square = function (n) {

return n*n;

};

arr.forEach( function(v, i) {

arr[i] = square(v);

});

SD4x-3.8 557

Page 558: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Arrow Functions

• New syntax for defining functions using arrows

• ES5 Syntax:var arr = [1,2,3,4,5];

var square = function (n) {

return n*n;

};

arr.forEach( function(v, i) {

arr[i] = square(v);

});

SD4x-3.8 558

Page 559: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Arrow Functions

• New syntax for defining functions using arrows

• ES5 Syntax:var arr = [1,2,3,4,5];

var square = function (n) {

return n*n;

};

arr.forEach( function(v, i) {

arr[i] = square(v);

});

SD4x-3.8 559

Page 560: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Arrow Functions

• New syntax for defining functions using arrows

• ES5 Syntax:

• ES6 Syntax:

var arr = [1,2,3,4,5];

var square = function (n) {

return n*n;

};

arr.forEach( function(v, i) {

arr[i] = square(v);

});

let arr = [1,2,3,4,5];

let square = n => {

return n*n;

};

arr.forEach( (v, i) => {

arr[i] = square(v);

});

SD4x-3.8 560

Page 561: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Arrow Functions

• New syntax for defining functions using arrows

• ES5 Syntax:

• ES6 Syntax:

var arr = [1,2,3,4,5];

var square = function (n) {

return n*n;

};

arr.forEach( function(v, i) {

arr[i] = square(v);

});

let arr = [1,2,3,4,5];

let square = n => {

return n*n;

};

arr.forEach( (v, i) => {

arr[i] = square(v);

});

SD4x-3.8 561

Page 562: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Arrow Functions

• New syntax for defining functions using arrows

• ES5 Syntax:

• ES6 Syntax:

var arr = [1,2,3,4,5];

var square = function (n) {

return n*n;

};

arr.forEach( function(v, i) {

arr[i] = square(v);

});

let arr = [1,2,3,4,5];

let square = n => {

return n*n;

};

arr.forEach( (v, i) => {

arr[i] = square(v);

});

SD4x-3.8 562

Page 563: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Arrow Functions

• New syntax for defining functions using arrows

• ES5 Syntax:

• ES6 Syntax:

var arr = [1,2,3,4,5];

var square = function (n) {

return n*n;

};

arr.forEach( function(v, i) {

arr[i] = square(v);

});

let arr = [1,2,3,4,5];

let square = n => {

return n*n;

};

arr.forEach( (v, i) => {

arr[i] = square(v);

});

SD4x-3.8 563

Page 564: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Arrow Functions

• New syntax for defining functions using arrows

• ES5 Syntax:

• ES6 Syntax:

var arr = [1,2,3,4,5];

var square = function (n) {

return n*n;

};

arr.forEach( function(v, i) {

arr[i] = square(v);

});

let arr = [1,2,3,4,5];

let square = n => {

return n*n;

};

arr.forEach( (v, i) => {

arr[i] = square(v);

});

SD4x-3.8 564

Page 565: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Default Parameter Values

• The “=“ symbol can be used to assign default values to function parameters

function pow (base, power = 2) {

return Math.pow(base, power);

};

SD4x-3.8 565

Page 566: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Default Parameter Values

• The “=“ symbol can be used to assign default values to function parameters

function pow (base, power = 2) {

return Math.pow(base, power);

};

SD4x-3.8 566

Page 567: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Default Parameter Values

• The “=“ symbol can be used to assign default values to function parameters

function pow (base, power = 2) {

return Math.pow(base, power);

};

SD4x-3.8 567

Page 568: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Default Parameter Values

• The “=“ symbol can be used to assign default values to function parameters

function pow (base, power = 2) {

return Math.pow(base, power);

};

console.log(pow(3));

SD4x-3.8 568

Page 569: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Default Parameter Values

• The “=“ symbol can be used to assign default values to function parameters

function pow (base, power = 2) {

return Math.pow(base, power);

};

console.log(pow(3));

SD4x-3.8 569

Page 570: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Default Parameter Values

• The “=“ symbol can be used to assign default values to function parameters

function pow (base, power = 2) {

return Math.pow(base, power);

};

console.log(pow(3));

SD4x-3.8 570

Page 571: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Default Parameter Values

• The “=“ symbol can be used to assign default values to function parameters

function pow (base, power = 2) {

return Math.pow(base, power);

};

console.log(pow(3)); // 9

SD4x-3.8 571

Page 572: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Default Parameter Values

• The “=“ symbol can be used to assign default values to function parameters

function pow (base, power = 2) {

return Math.pow(base, power);

};

console.log(pow(3)); // 9

console.log(pow(3,3));

SD4x-3.8 572

Page 573: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Default Parameter Values

• The “=“ symbol can be used to assign default values to function parameters

function pow (base, power = 2) {

return Math.pow(base, power);

};

console.log(pow(3)); // 9

console.log(pow(3,3));

SD4x-3.8 573

Page 574: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Default Parameter Values

• The “=“ symbol can be used to assign default values to function parameters

function pow (base, power = 2) {

return Math.pow(base, power);

};

console.log(pow(3)); // 9

console.log(pow(3,3)); // 27

SD4x-3.8 574

Page 575: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Template Literals

• Can define a template for rendering strings

• ES5 Syntax:

var person = { name: "Lydia" };

var msg = "Dear " + person.name + ",\n" + "How are you? ";

SD4x-3.8 575

Page 576: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Template Literals

• Can define a template for rendering strings

• ES5 Syntax:

var person = { name: "Lydia" };

var msg = "Dear " + person.name + ",\n" + "How are you? ";

SD4x-3.8 576

Page 577: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Template Literals

• Can define a template for rendering strings

• ES5 Syntax:

var person = { name: "Lydia" };

var msg = "Dear " + person.name + ",\n" + "How are you? ";

SD4x-3.8 577

Page 578: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Template Literals

• Can define a template for rendering strings

• ES5 Syntax:

var person = { name: "Lydia" };

var msg = "Dear " + person.name + ",\n" + "How are you? ";

SD4x-3.8 578

Page 579: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Template Literals

• Can define a template for rendering strings

• ES5 Syntax:

var person = { name: "Lydia" };

var msg = "Dear " + person.name + ",\n" + "How are you? ";

SD4x-3.8 579

Page 580: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Template Literals

• Can define a template for rendering strings

• ES5 Syntax:

• ES6 Syntax:

var person = { name: "Lydia" };

var msg = "Dear " + person.name + ",\n" + "How are you? ";

var person = { name: "Lydia" };

var msg = ‘Dear ${person.name},

How are you?‘

SD4x-3.8 580

Page 581: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Template Literals

• Can define a template for rendering strings

• ES5 Syntax:

• ES6 Syntax:

var person = { name: "Lydia" };

var msg = "Dear " + person.name + ",\n" + "How are you? ";

var person = { name: "Lydia" };

var msg = ‘Dear ${person.name},

How are you?‘

SD4x-3.8 581

Page 582: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Template Literals

• Can define a template for rendering strings

• ES5 Syntax:

• ES6 Syntax:

var person = { name: "Lydia" };

var msg = "Dear " + person.name + ",\n" + "How are you? ";

var person = { name: "Lydia" };

var msg = ‘Dear ${person.name},

How are you?‘

SD4x-3.8 582

Page 583: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Template Literals

• Can define a template for rendering strings

• ES5 Syntax:

• ES6 Syntax:

var person = { name: "Lydia" };

var msg = "Dear " + person.name + ",\n" + "How are you? ";

var person = { name: "Lydia" };

var msg = ‘Dear ${person.name},

How are you?‘

SD4x-3.8 583

Page 584: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Template Literals

• Can define a template for rendering strings

• ES5 Syntax:

• ES6 Syntax:

var person = { name: "Lydia" };

var msg = "Dear " + person.name + ",\n" + "How are you? ";

var person = { name: "Lydia" };

var msg = ‘Dear ${person.name},

How are you?‘

SD4x-3.8 584

Page 585: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Classes

• Instead of building prototypes, ES6 allows classes to be directly defined in more traditional OOP style

• ES5 Syntax: var Rectangle = function (height, width) {

this.height = height;

this.width = width;

}

Rectangle.prototype.area = function () {

return this.height * this.width;

}

SD4x-3.8 585

Page 586: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Classes

• Instead of building prototypes, ES6 allows classes to be directly defined in more traditional OOP style

• ES5 Syntax: var Rectangle = function (height, width) {

this.height = height;

this.width = width;

}

Rectangle.prototype.area = function () {

return this.height * this.width;

}

SD4x-3.8 586

Page 587: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Classes

• Instead of building prototypes, ES6 allows classes to be directly defined in more traditional OOP style

• ES5 Syntax: var Rectangle = function (height, width) {

this.height = height;

this.width = width;

}

Rectangle.prototype.area = function () {

return this.height * this.width;

}

SD4x-3.8 587

Page 588: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Classes

• Instead of building prototypes, ES6 allows classes to be directly defined in more traditional OOP style

• ES5 Syntax:

• ES6 Syntax:

var Rectangle = function (height, width) {

this.height = height;

this.width = width;

}

Rectangle.prototype.area = function () {

return this.height * this.width;

}

class Rectangle {

constructor (height, width) {

this.height = height;

this.width = width;

}

area () {

return this.height * this.width;

}

}

SD4x-3.8 588

Page 589: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Classes

• Instead of building prototypes, ES6 allows classes to be directly defined in more traditional OOP style

• ES5 Syntax:

• ES6 Syntax:

var Rectangle = function (height, width) {

this.height = height;

this.width = width;

}

Rectangle.prototype.area = function () {

return this.height * this.width;

}

class Rectangle {

constructor (height, width) {

this.height = height;

this.width = width;

}

area () {

return this.height * this.width;

}

}

SD4x-3.8 589

Page 590: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Classes

• Instead of building prototypes, ES6 allows classes to be directly defined in more traditional OOP style

• ES5 Syntax:

• ES6 Syntax:

var Rectangle = function (height, width) {

this.height = height;

this.width = width;

}

Rectangle.prototype.area = function () {

return this.height * this.width;

}

class Rectangle {

constructor (height, width) {

this.height = height;

this.width = width;

}

area () {

return this.height * this.width;

}

}

SD4x-3.8 590

Page 591: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Classes

• Instead of building prototypes, ES6 allows classes to be directly defined in more traditional OOP style

• ES5 Syntax:

• ES6 Syntax:

var Rectangle = function (height, width) {

this.height = height;

this.width = width;

}

Rectangle.prototype.area = function () {

return this.height * this.width;

}

class Rectangle {

constructor (height, width) {

this.height = height;

this.width = width;

}

area () {

return this.height * this.width;

}

}

SD4x-3.8 591

Page 592: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Classes

• Instead of building prototypes, ES6 allows classes to be directly defined in more traditional OOP style

• ES5 Syntax:

• ES6 Syntax:

var Rectangle = function (height, width) {

this.height = height;

this.width = width;

}

Rectangle.prototype.area = function () {

return this.height * this.width;

}

class Rectangle {

constructor (height, width) {

this.height = height;

this.width = width;

}

area () {

return this.height * this.width;

}

}

SD4x-3.8 592

Page 593: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 – Classes

• Instead of building prototypes, ES6 allows classes to be directly defined in more traditional OOP style

• ES5 Syntax:

• ES6 Syntax:

var Rectangle = function (height, width) {

this.height = height;

this.width = width;

}

Rectangle.prototype.area = function () {

return this.height * this.width;

}

class Rectangle {

constructor (height, width) {

this.height = height;

this.width = width;

}

area () {

return this.height * this.width;

}

}

SD4x-3.8 593

Page 594: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Sets

• ES6 introduces a Set class

• Elements are distinct and maintain order

let s = new Set();

s.add("alligator"); // s = {"alligator"}

s.add("dolphin"); // s = {"alligator", "dolphin"}

s.add("fox"); // s = {"alligator", "dolphin", "fox"}

s.add("alligator"); // s = {"alligator", "dolphin", "fox"}

s.has("alligator"); // true

s.delete("alligator"); // s = {"dolphin", "fox"}

for (let v of s.values())

console.log(v); // prints each value in order

SD4x-3.8 594

Page 595: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Sets

• ES6 introduces a Set class

• Elements are distinct and maintain order

let s = new Set();

s.add("alligator"); // s = {"alligator"}

s.add("dolphin"); // s = {"alligator", "dolphin"}

s.add("fox"); // s = {"alligator", "dolphin", "fox"}

s.add("alligator"); // s = {"alligator", "dolphin", "fox"}

s.has("alligator"); // true

s.delete("alligator"); // s = {"dolphin", "fox"}

for (let v of s.values())

console.log(v); // prints each value in order

SD4x-3.8 595

Page 596: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Sets

• ES6 introduces a Set class

• Elements are distinct and maintain order

let s = new Set();

s.add("alligator"); // s = {"alligator"}

s.add("dolphin"); // s = {"alligator", "dolphin"}

s.add("fox"); // s = {"alligator", "dolphin", "fox"}

s.add("alligator"); // s = {"alligator", "dolphin", "fox"}

s.has("alligator"); // true

s.delete("alligator"); // s = {"dolphin", "fox"}

for (let v of s.values())

console.log(v); // prints each value in order

SD4x-3.8 596

Page 597: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Sets

• ES6 introduces a Set class

• Elements are distinct and maintain order

let s = new Set();

s.add("alligator"); // s = {"alligator"}

s.add("dolphin"); // s = {"alligator", "dolphin"}

s.add("fox"); // s = {"alligator", "dolphin", "fox"}

s.add("alligator"); // s = {"alligator", "dolphin", "fox"}

s.has("alligator"); // true

s.delete("alligator"); // s = {"dolphin", "fox"}

for (let v of s.values())

console.log(v); // prints each value in order

SD4x-3.8 597

Page 598: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Sets

• ES6 introduces a Set class

• Elements are distinct and maintain order

let s = new Set();

s.add("alligator"); // s = {"alligator"}

s.add("dolphin"); // s = {"alligator", "dolphin"}

s.add("fox"); // s = {"alligator", "dolphin", "fox"}

s.add("alligator"); // s = {"alligator", "dolphin", "fox"}

s.has("alligator"); // true

s.delete("alligator"); // s = {"dolphin", "fox"}

for (let v of s.values())

console.log(v); // prints each value in order

SD4x-3.8 598

Page 599: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Sets

• ES6 introduces a Set class

• Elements are distinct and maintain order

let s = new Set();

s.add("alligator"); // s = {"alligator"}

s.add("dolphin"); // s = {"alligator", "dolphin"}

s.add("fox"); // s = {"alligator", "dolphin", "fox"}

s.add("alligator"); // s = {"alligator", "dolphin", "fox"}

s.has("alligator"); // true

s.delete("alligator"); // s = {"dolphin", "fox"}

for (let v of s.values())

console.log(v); // prints each value in order

SD4x-3.8 599

Page 600: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Sets

• ES6 introduces a Set class

• Elements are distinct and maintain order

let s = new Set();

s.add("alligator"); // s = {"alligator"}

s.add("dolphin"); // s = {"alligator", "dolphin"}

s.add("fox"); // s = {"alligator", "dolphin", "fox"}

s.add("alligator"); // s = {"alligator", "dolphin", "fox"}

s.has("alligator"); // true

s.delete("alligator"); // s = {"dolphin", "fox"}

for (let v of s.values())

console.log(v); // prints each value in order

SD4x-3.8 600

Page 601: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Sets

• ES6 introduces a Set class

• Elements are distinct and maintain order

let s = new Set();

s.add("alligator"); // s = {"alligator"}

s.add("dolphin"); // s = {"alligator", "dolphin"}

s.add("fox"); // s = {"alligator", "dolphin", "fox"}

s.add("alligator"); // s = {"alligator", "dolphin", "fox"}

s.has("alligator"); // true

s.delete("alligator"); // s = {"dolphin", "fox"}

for (let v of s.values())

console.log(v); // prints each value in order

SD4x-3.8 601

Page 602: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Sets

• ES6 introduces a Set class

• Elements are distinct and maintain order

let s = new Set();

s.add("alligator"); // s = {"alligator"}

s.add("dolphin"); // s = {"alligator", "dolphin"}

s.add("fox"); // s = {"alligator", "dolphin", "fox"}

s.add("alligator"); // s = {"alligator", "dolphin", "fox"}

s.has("alligator"); // true

s.delete("alligator"); // s = {"dolphin", "fox"}

for (let v of s.values())

console.log(v); // prints each value in order

SD4x-3.8 602

Page 603: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Sets

• ES6 introduces a Set class

• Elements are distinct and maintain order

let s = new Set();

s.add("alligator"); // s = {"alligator"}

s.add("dolphin"); // s = {"alligator", "dolphin"}

s.add("fox"); // s = {"alligator", "dolphin", "fox"}

s.add("alligator"); // s = {"alligator", "dolphin", "fox"}

s.has("alligator"); // true

s.delete("alligator"); // s = {"dolphin", "fox"}

for (let v of s.values())

console.log(v); // prints each value in order

SD4x-3.8 603

Page 604: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Maps

• ES6 also introduces a Map class

• A Set of keys is mapped to corresponding values

let m = new Map();

m.set("dog", "rover"); // {"dog" => "rover"}

m.set("cat", "felix"); // {"dog" => "rover", "cat" => "felix"}

m.get("cat"); // "felix"

m.get("mouse"); // undefined

for (let [key, val] of m.entries())

console.log(key + ": " + val); // prints keys and values

SD4x-3.8 604

Page 605: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Maps

• ES6 also introduces a Map class

• A Set of keys is mapped to corresponding values

let m = new Map();

m.set("dog", "rover"); // {"dog" => "rover"}

m.set("cat", "felix"); // {"dog" => "rover", "cat" => "felix"}

m.get("cat"); // "felix"

m.get("mouse"); // undefined

for (let [key, val] of m.entries())

console.log(key + ": " + val); // prints keys and values

SD4x-3.8 605

Page 606: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Maps

• ES6 also introduces a Map class

• A Set of keys is mapped to corresponding values

let m = new Map();

m.set("dog", "rover"); // {"dog" => "rover"}

m.set("cat", "felix"); // {"dog" => "rover", "cat" => "felix"}

m.get("cat"); // "felix"

m.get("mouse"); // undefined

for (let [key, val] of m.entries())

console.log(key + ": " + val); // prints keys and values

SD4x-3.8 606

Page 607: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Maps

• ES6 also introduces a Map class

• A Set of keys is mapped to corresponding values

let m = new Map();

m.set("dog", "rover"); // {"dog" => "rover"}

m.set("cat", "felix"); // {"dog" => "rover", "cat" => "felix"}

m.get("cat"); // "felix"

m.get("mouse"); // undefined

for (let [key, val] of m.entries())

console.log(key + ": " + val); // prints keys and values

SD4x-3.8 607

Page 608: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Maps

• ES6 also introduces a Map class

• A Set of keys is mapped to corresponding values

let m = new Map();

m.set("dog", "rover"); // {"dog" => "rover"}

m.set("cat", "felix"); // {"dog" => "rover", "cat" => "felix"}

m.get("cat"); // "felix"

m.get("mouse"); // undefined

for (let [key, val] of m.entries())

console.log(key + ": " + val); // prints keys and values

SD4x-3.8 608

Page 609: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Maps

• ES6 also introduces a Map class

• A Set of keys is mapped to corresponding values

let m = new Map();

m.set("dog", "rover"); // {"dog" => "rover"}

m.set("cat", "felix"); // {"dog" => "rover", "cat" => "felix"}

m.get("cat"); // "felix"

m.get("mouse"); // undefined

for (let [key, val] of m.entries())

console.log(key + ": " + val); // prints keys and values

SD4x-3.8 609

Page 610: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Maps

• ES6 also introduces a Map class

• A Set of keys is mapped to corresponding values

let m = new Map();

m.set("dog", "rover"); // {"dog" => "rover"}

m.set("cat", "felix"); // {"dog" => "rover", "cat" => "felix"}

m.get("cat"); // "felix"

m.get("mouse"); // undefined

for (let [key, val] of m.entries())

console.log(key + ": " + val); // prints keys and values

SD4x-3.8 610

Page 611: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

ES6 Data Structures: Maps

• ES6 also introduces a Map class

• A Set of keys is mapped to corresponding values

let m = new Map();

m.set("dog", "rover"); // {"dog" => "rover"}

m.set("cat", "felix"); // {"dog" => "rover", "cat" => "felix"}

m.get("cat"); // "felix"

m.get("mouse"); // undefined

for (let [key, val] of m.entries())

console.log(key + ": " + val); // prints keys and values

SD4x-3.8 611

Page 612: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Summary

• ES6 provides simplified syntax and new libraries and functionality

• We will use ES6 notation in the remaining lessons in the course

SD4x-3.8 612

Page 613: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Video 3.9

D3 Intro

Chris Murphy

SD4x-3.9 613

Page 614: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Review

• We can use JavaScript to dynamically modify/create HTML elements in Web pages

• jQuery provides a simpler syntax and other additional features

• React allows us to create reusable, modular components

SD4x-3.9 614

Page 615: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Standard SVG

• We can render basic visual elements in HTML using Scalable Vector Graphics (SVG)

• These are HTML elements that are included in the Web page

• They do not lose quality when the page is resized

• SVG elements are part of the DOM, so their attributes can be modified by CSS and JavaScript

SD4x-3.9 615

Page 616: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.9 616

Page 617: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.9 617

Page 618: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.9 618

Page 619: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.9 619

Page 620: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.9 620

Page 621: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<style>

circle:hover {

fill:green;

};

</style>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

<rect x="50" y="20" rx="20" ry="20"

width="150" height="150"

style="fill:red;stroke:black;stroke-width:5;opacity:0.5"

onclick="style.fill='cyan'" />

</svg>

</body>

</html>

SD4x-3.9 621

Page 622: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<style>

circle:hover {

fill:green;

};

</style>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

<rect x="50" y="20" rx="20" ry="20"

width="150" height="150"

style="fill:red;stroke:black;stroke-width:5;opacity:0.5"

onclick="style.fill='cyan'" />

</svg>

</body>

</html>

SD4x-3.9 622

Page 623: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<style>

circle:hover {

fill:green;

};

</style>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

<rect x="50" y="20" rx="20" ry="20"

width="150" height="150"

style="fill:red;stroke:black;stroke-width:5;opacity:0.5"

onclick="style.fill='cyan'" />

</svg>

</body>

</html>

SD4x-3.9 623

Page 624: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<style>

circle:hover {

fill:green;

};

</style>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

<rect x="50" y="20" rx="20" ry="20"

width="150" height="150"

style="fill:red;stroke:black;stroke-width:5;opacity:0.5"

onclick="style.fill='cyan'" />

</svg>

</body>

</html>

SD4x-3.9 624

Page 625: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<style>

circle:hover {

fill:green;

};

</style>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

<rect x="50" y="20" rx="20" ry="20"

width="150" height="150"

style="fill:red;stroke:black;stroke-width:5;opacity:0.5"

onclick="style.fill='cyan'" />

</svg>

</body>

</html>

SD4x-3.9 625

Page 626: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.9 626

50

Page 627: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.9 627

50

50

Page 628: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.9 628

50

50

Page 629: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<style>

circle:hover {

fill:green;

};

</style>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

<rect x="50" y="20" rx="20" ry="20"

width="150" height="150"

style="fill:red;stroke:black;stroke-width:5;opacity:0.5"

onclick="style.fill='cyan'" />

</svg>

</body>

</html>

SD4x-3.9 629

Page 630: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<style>

circle:hover {

fill:green;

};

</style>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

<rect x="50" y="20" rx="20" ry="20"

width="150" height="150"

style="fill:red;stroke:black;stroke-width:5;opacity:0.5"

onclick="style.fill='cyan'" />

</svg>

</body>

</html>

SD4x-3.9 630

Page 631: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<style>

circle:hover {

fill:green;

};

</style>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

<rect x="50" y="20" rx="20" ry="20"

width="150" height="150"

style="fill:red;stroke:black;stroke-width:5;opacity:0.5"

onclick="style.fill='cyan'" />

</svg>

</body>

</html>

SD4x-3.9 631

Page 632: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<style>

circle:hover {

fill:green;

};

</style>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

<rect x="50" y="20" rx="20" ry="20"

width="150" height="150"

style="fill:red;stroke:black;stroke-width:5;opacity:0.5"

onclick="style.fill='cyan'" />

</svg>

</body>

</html>

SD4x-3.9 632

Page 633: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<style>

circle:hover {

fill:green;

};

</style>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

<rect x="50" y="20" rx="20" ry="20"

width="150" height="150"

style="fill:red;stroke:black;stroke-width:5;opacity:0.5"

onclick="style.fill='cyan'" />

</svg>

</body>

</html>

SD4x-3.9 633

Page 634: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<style>

circle:hover {

fill:green;

};

</style>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

<rect x="50" y="20" rx="20" ry="20"

width="150" height="150"

style="fill:red;stroke:black;stroke-width:5;opacity:0.5"

onclick="style.fill='cyan'" />

</svg>

</body>

</html>

SD4x-3.9 634

Page 635: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<style>

circle:hover {

fill:green;

};

</style>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

<rect x="50" y="20" rx="20" ry="20"

width="150" height="150"

style="fill:red;stroke:black;stroke-width:5;opacity:0.5"

onclick="style.fill='cyan'" />

</svg>

</body>

</html>

SD4x-3.9 635

Page 636: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<style>

circle:hover {

fill:green;

};

</style>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

<rect x="50" y="20" rx="20" ry="20"

width="150" height="150"

style="fill:red;stroke:black;stroke-width:5;opacity:0.5"

onclick="style.fill='cyan'" />

</svg>

</body>

</html>

SD4x-3.9 636

Page 637: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Dynamic SVG

• Since SVG elements are part of the DOM, we can use JavaScript to manipulate their attributes

• But we may also want to dynamically generate SVG elements based on user actions, data received from an API, etc.

SD4x-3.9 637

Page 638: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

D3: Data-Driven Documents

• D3.js is a JavaScript library for manipulating HTML documents based on data

• Data can be bound to DOM elements (HTML, SVG) and then we can programmatically apply data-driven transformations

• This can be used for generating HTML tables, SVG charts and graphs, etc.

SD4x-3.9 638

Page 639: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

</svg>

</body>

</html>

SD4x-3.9 639

Page 640: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

</svg>

</body>

</html>

SD4x-3.9 640

Page 641: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

</head>

<body>

<svg width="400" height="400">

<circle cx="50" cy="50" r="40"

stroke="blue" stroke-width="4" fill="yellow" />

</svg>

</body>

</html>

SD4x-3.9 641

Page 642: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg width="400" height="400">

<circle />

</svg>

<script>

// next slide -->

</script>

</body>

</html>

SD4x-3.9 642

Page 643: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg width="400" height="400">

<circle />

</svg>

<script>

// next slide -->

</script>

</body>

</html>

SD4x-3.9 643

Page 644: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg width="400" height="400">

<circle />

</svg>

<script>

// next slide -->

</script>

</body>

</html>

SD4x-3.9 644

Page 645: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg width="400" height="400">

<circle />

</svg>

<script>

// next slide -->

</script>

</body>

</html>

SD4x-3.9 645

Page 646: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg width="400" height="400">

<circle />

</svg>

<script>

// next slide -->

</script>

</body>

</html>

SD4x-3.9 646

Page 647: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 647

Page 648: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 648

Page 649: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 649

Page 650: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 650

Page 651: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 651

Page 652: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 652

Page 653: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 653

Page 654: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 654

Page 655: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 655

Page 656: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 656

Page 657: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 657

Page 658: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 658

Page 659: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 659

Page 660: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 660

Page 661: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 661

Page 662: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 662

Page 663: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 663

Page 664: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 664

Page 665: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 665

Page 666: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 666

Page 667: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4,

fill: 'yellow'

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 667

Page 668: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 668

Page 669: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", circle.fill);

</script>

SD4x-3.9 669

Page 670: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", () => {

if (circle.r < 50) return 'yellow';

else return 'cyan'; })

</script>

SD4x-3.9 670

Page 671: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", () => {

if (circle.r < 50) return 'yellow';

else return 'cyan'; })

</script>

SD4x-3.9 671

Page 672: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", () => {

if (circle.r < 50) return 'yellow';

else return 'cyan'; })

</script>

SD4x-3.9 672

Page 673: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", () => {

if (circle.r < 50) return 'yellow';

else return 'cyan'; })

</script>

SD4x-3.9 673

Page 674: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script>

var circle = {

x: 50,

y: 50,

r: 40,

stroke: 'blue',

width: 4

};

var svg = d3.select("svg");

svg.select("circle")

.attr("cx", circle.x)

.attr("cy", circle.y)

.attr("r", circle.r)

.style("stroke", circle.stroke)

.style("stroke-width", circle.width);

.style("fill", () => {

if (circle.r < 50) return 'yellow';

else return 'cyan'; })

</script>

SD4x-3.9 674

Page 675: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Summary

• We can render basic visual elements in HTML using Scalable Vector Graphics (SVG)

• We can use D3.js to programmatically generate HTML elements (including SVG) based on data

SD4x-3.9 675

Page 676: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Video 3.10

D3 Charts

Chris Murphy

SD4x-3.10 676

Page 677: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Review

• D3.js allows us to programmatically generate HTML elements (including SVG) based on data

• The most common visual representation of data is in the form of a chart

SD4x-3.10 677

Page 678: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 678

Page 679: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 679

Page 680: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 680

Page 681: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 681

Page 682: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 682

Page 683: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 683

Page 684: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 684

Page 685: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 685

Page 686: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 686

Page 687: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 687

Page 688: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 688

Page 689: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 689

Page 690: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 690

Page 691: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 691

Page 692: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 692

Page 693: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 693

Page 694: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 694

160

Page 695: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 695

160

40

Page 696: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 696

160

Page 697: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 697

7040

Page 698: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 698

125

80

Page 699: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 699

Page 700: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

rect {

fill: darkred;

}

rect:hover {

fill: darkblue;

}

.chart text {

fill: white;

font: 10px sans-serif;

text-anchor: end;

}

</style>

<svg class="chart" height="200">

<g transform="translate(0,160)">

<rect width="39" height="40"></rect><text x="25" y="10">4</text>

</g>

<g transform="translate(40,70)">

<rect width="39" height="130"></rect><text x="25" y="10">13</text>

</g>

<g transform="translate(80,125)">

<rect width="39" height="75"></rect><text x="25" y="10">7.5</text>

</g>

<g transform="translate(120,30)">

<rect width="39" height="170"></rect><text x="25" y="10">17</text>

</g>

</svg>

SD4x-3.10 700

Page 701: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Dynamic SVG with D3.js

• D3.js is specifically designed to allow us to manipulate HTML/SVG elements based on data

• We can dynamically render SVG elements by applying functionality to a set of data

SD4x-3.10 701

Page 702: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 702

Page 703: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 703

Page 704: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 704

Page 705: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 705

Page 706: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 706

Page 707: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 707

Page 708: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 708

Page 709: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 709

Page 710: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 710

Page 711: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 711

Page 712: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 712

Page 713: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 713

Page 714: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 714

Page 715: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 715

var numbers = [40, 130, 75, 170];

Page 716: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 716

var numbers = [40, 130, 75, 170];

Page 717: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 717

var numbers = [40, 130, 75, 170];160

Page 718: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 718

var numbers = [40, 130, 75, 170];160

d = 40, i = 0 x = 0, y = 160

Page 719: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 719

var numbers = [40, 130, 75, 170];70

d = 40, i = 0 x = 0, y = 160

d = 130, i = 1 x = 40, y = 70

40

Page 720: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 720

var numbers = [40, 130, 75, 170];125

d = 40, i = 0 x = 0, y = 160

d = 130, i = 1 x = 40, y = 70

d = 75, i = 2 x = 80, y = 125

80

Page 721: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 721

var numbers = [40, 130, 75, 170];

30

d = 40, i = 0 x = 0, y = 160

d = 130, i = 1 x = 40, y = 70

d = 75, i = 2 x = 80, y = 125

d = 170, i = 3 x = 120, y = 30

120

Page 722: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 722

var numbers = [40, 130, 75, 170];

d = 40, i = 0 x = 0, y = 160

d = 130, i = 1 x = 40, y = 70

d = 75, i = 2 x = 80, y = 125

d = 170, i = 3 x = 120, y = 30

Page 723: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 723

var numbers = [40, 130, 75, 170];

d = 40, i = 0 x = 0, y = 160

d = 130, i = 1 x = 40, y = 70

d = 75, i = 2 x = 80, y = 125

d = 170, i = 3 x = 120, y = 30

Page 724: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 724

var numbers = [40, 130, 75, 170];

d = 40, i = 0 x = 0, y = 160

d = 130, i = 1 x = 40, y = 70

d = 75, i = 2 x = 80, y = 125

d = 170, i = 3 x = 120, y = 30

Page 725: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 725

Page 726: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 726

Page 727: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 727

Page 728: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 728

Page 729: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 729

Page 730: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 730

Page 731: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 731

Page 732: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 732

Page 733: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 733

Page 734: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<style>

<!-- same CSS as before -->

</style>

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<script>

var numbers = [40, 130, 75, 170];

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(numbers)

.enter().append("g")

.attr("transform", (d,i) => {

return "translate(" + 40*i + "," + (200-d) + ")"; });

selection.append("rect")

.attr("width", 39)

.attr("height", (d,i) => { return d; });

selection.append("text")

.attr("x", 25)

.attr("y", 25)

.text((d) => { return d/10; });

</script>

SD4x-3.10 734

Page 735: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Dynamic Graphics with D3.js

• In addition to rendering HTML/SVG elements using JavaScript, D3.js also allows us to add elements based on any changes to the data

• This allows us to dynamically modify our chart and other graphics

SD4x-3.10 735

Page 736: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 736

Page 737: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 737

Page 738: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 738

Page 739: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 739

Page 740: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.10 740

Page 741: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 741

Page 742: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 742

Page 743: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 743

Page 744: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 744

Page 745: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 745

Page 746: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 746

Page 747: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 747

Page 748: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 748

Page 749: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 749

Page 750: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 750

Page 751: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 751

Page 752: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 752

Page 753: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 753

Page 754: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 754

Page 755: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<script src="http://d3js.org/d3.v4.min.js"></script>

<svg class="chart" height="200"></svg>

<p>

<input id="inputField"></input>

<button onclick="insert();">Insert</button>

<script>

var numbers = [40, 130, 75, 170];

function insert() {

var value = document.getElementById('inputField').value;

numbers.push(value);

drawChart();

document.getElementById('inputField').value = '';

}

function drawChart() {

// same D3 code as before!

}

drawChart();

</script>

SD4x-3.10 755

Page 756: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Summary

• D3.js is a powerful library for generating HTML and SVG elements based on data

• We can apply functions to data sets to generate graphical elements, e.g. charts

• And use D3.js to modify the elements when new data is added

SD4x-3.10 756

Page 757: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Video 3.11

More D3

Chris Murphy

SD4x-3.11 757

Page 758: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Review

• D3.js allows us to generate HTML and SVG elements based on data

• We can apply functions to data sets to generate graphical elements, e.g. charts

SD4x-3.11 758

Page 759: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 759

Page 760: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

D3 and Data

• The data used in D3 can be objects, not just numbers

• We can then use the properties of these objects when deciding how to render the visualization (chart, SVG, etc.)

SD4x-3.11 760

Page 761: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg class="chart" height="900" width="900">

</svg>

<script>

var values = [

{price: 700, sqft: 3000, br: 3, pets: [ 'cats', 'dogs' ] },

{price: 445, sqft: 1700, br: 2, pets: [] },

{price: 421, sqft: 1455, br: 2, pets: [ 'cats', 'dogs' ] },

{price: 411, sqft: 1314, br: 2, pets: [ 'dogs' ] },

{price: 275, sqft: 1200, br: 1, pets: [ 'cats' ]},

{price: 500, sqft: 650, br: 1, pets: [] },

];

. . .

SD4x-3.11 761

Page 762: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg class="chart" height="900" width="900">

</svg>

<script>

var values = [

{price: 700, sqft: 3000, br: 3, pets: [ 'cats', 'dogs' ] },

{price: 445, sqft: 1700, br: 2, pets: [] },

{price: 421, sqft: 1455, br: 2, pets: [ 'cats', 'dogs' ] },

{price: 411, sqft: 1314, br: 2, pets: [ 'dogs' ] },

{price: 275, sqft: 1200, br: 1, pets: [ 'cats' ]},

{price: 500, sqft: 650, br: 1, pets: [] },

];

. . .

SD4x-3.11 762

Page 763: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg class="chart" height="900" width="900">

</svg>

<script>

var values = [

{price: 700, sqft: 3000, br: 3, pets: [ 'cats', 'dogs' ] },

{price: 445, sqft: 1700, br: 2, pets: [] },

{price: 421, sqft: 1455, br: 2, pets: [ 'cats', 'dogs' ] },

{price: 411, sqft: 1314, br: 2, pets: [ 'dogs' ] },

{price: 275, sqft: 1200, br: 1, pets: [ 'cats' ]},

{price: 500, sqft: 650, br: 1, pets: [] },

];

. . .

SD4x-3.11 763

Page 764: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg class="chart" height="900" width="900">

</svg>

<script>

var values = [

{price: 700, sqft: 3000, br: 3, pets: [ 'cats', 'dogs' ] },

{price: 445, sqft: 1700, br: 2, pets: [] },

{price: 421, sqft: 1455, br: 2, pets: [ 'cats', 'dogs' ] },

{price: 411, sqft: 1314, br: 2, pets: [ 'dogs' ] },

{price: 275, sqft: 1200, br: 1, pets: [ 'cats' ]},

{price: 500, sqft: 650, br: 1, pets: [] },

];

. . .

SD4x-3.11 764

Page 765: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg class="chart" height="900" width="900">

</svg>

<script>

var values = [

{price: 700, sqft: 3000, br: 3, pets: [ 'cats', 'dogs' ] },

{price: 445, sqft: 1700, br: 2, pets: [] },

{price: 421, sqft: 1455, br: 2, pets: [ 'cats', 'dogs' ] },

{price: 411, sqft: 1314, br: 2, pets: [ 'dogs' ] },

{price: 275, sqft: 1200, br: 1, pets: [ 'cats' ]},

{price: 500, sqft: 650, br: 1, pets: [] },

];

. . .

SD4x-3.11 765

Page 766: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg class="chart" height="900" width="900">

</svg>

<script>

var values = [

{price: 700, sqft: 3000, br: 3, pets: [ 'cats', 'dogs' ] },

{price: 445, sqft: 1700, br: 2, pets: [] },

{price: 421, sqft: 1455, br: 2, pets: [ 'cats', 'dogs' ] },

{price: 411, sqft: 1314, br: 2, pets: [ 'dogs' ] },

{price: 275, sqft: 1200, br: 1, pets: [ 'cats' ]},

{price: 500, sqft: 650, br: 1, pets: [] },

];

. . .

SD4x-3.11 766

Page 767: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg class="chart" height="900" width="900">

</svg>

<script>

var values = [

{price: 700, sqft: 3000, br: 3, pets: [ 'cats', 'dogs' ] },

{price: 445, sqft: 1700, br: 2, pets: [] },

{price: 421, sqft: 1455, br: 2, pets: [ 'cats', 'dogs' ] },

{price: 411, sqft: 1314, br: 2, pets: [ 'dogs' ] },

{price: 275, sqft: 1200, br: 1, pets: [ 'cats' ]},

{price: 500, sqft: 650, br: 1, pets: [] },

];

. . .

SD4x-3.11 767

Page 768: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg class="chart" height="900" width="900">

</svg>

<script>

var values = [

{price: 700, sqft: 3000, br: 3, pets: [ 'cats', 'dogs' ] },

{price: 445, sqft: 1700, br: 2, pets: [] },

{price: 421, sqft: 1455, br: 2, pets: [ 'cats', 'dogs' ] },

{price: 411, sqft: 1314, br: 2, pets: [ 'dogs' ] },

{price: 275, sqft: 1200, br: 1, pets: [ 'cats' ]},

{price: 500, sqft: 650, br: 1, pets: [] },

];

. . .

SD4x-3.11 768

Page 769: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg class="chart" height="900" width="900">

</svg>

<script>

var values = [

{price: 700, sqft: 3000, br: 3, pets: [ 'cats', 'dogs' ] },

{price: 445, sqft: 1700, br: 2, pets: [] },

{price: 421, sqft: 1455, br: 2, pets: [ 'cats', 'dogs' ] },

{price: 411, sqft: 1314, br: 2, pets: [ 'dogs' ] },

{price: 275, sqft: 1200, br: 1, pets: [ 'cats' ]},

{price: 500, sqft: 650, br: 1, pets: [] },

];

. . .

SD4x-3.11 769

Page 770: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg class="chart" height="900" width="900">

</svg>

<script>

var values = [

{price: 700, sqft: 3000, br: 3, pets: [ 'cats', 'dogs' ] },

{price: 445, sqft: 1700, br: 2, pets: [] },

{price: 421, sqft: 1455, br: 2, pets: [ 'cats', 'dogs' ] },

{price: 411, sqft: 1314, br: 2, pets: [ 'dogs' ] },

{price: 275, sqft: 1200, br: 1, pets: [ 'cats' ]},

{price: 500, sqft: 650, br: 1, pets: [] },

];

. . .

SD4x-3.11 770

Page 771: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

<html>

<head>

<script src="http://d3js.org/d3.v4.min.js"></script>

</head>

<body>

<svg class="chart" height="900" width="900">

</svg>

<script>

var values = [

{price: 700, sqft: 3000, br: 3, pets: [ 'cats', 'dogs' ] },

{price: 445, sqft: 1700, br: 2, pets: [] },

{price: 421, sqft: 1455, br: 2, pets: [ 'cats', 'dogs' ] },

{price: 411, sqft: 1314, br: 2, pets: [ 'dogs' ] },

{price: 275, sqft: 1200, br: 1, pets: [ 'cats' ]},

{price: 500, sqft: 650, br: 1, pets: [] },

];

. . .

SD4x-3.11 771

Page 772: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 772

Page 773: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 773

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 774: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 774

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 775: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 775

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 776: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 776

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 777: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 777

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 778: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 778

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 779: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 779

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 780: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 780

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 781: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 781

Page 782: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 782

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 783: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 783

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 784: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 784

Page 785: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 785

{price: 700, sqft: 3000, . . . },

{price: 445, sqft: 1700, . . . },

{price: 421, sqft: 1455, . . . },

{price: 411, sqft: 1314, . . . },

{price: 275, sqft: 1200, . . . },

{price: 500, sqft: 650, . . . },

Page 786: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 786

{price: 700, sqft: 3000, . . . },

{price: 445, sqft: 1700, . . . },

{price: 421, sqft: 1455, . . . },

{price: 411, sqft: 1314, . . . },

{price: 275, sqft: 1200, . . . },

{price: 500, sqft: 650, . . . },

Page 787: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 787

{price: 700, sqft: 3000, . . . },

{price: 445, sqft: 1700, . . . },

{price: 421, sqft: 1455, . . . },

{price: 411, sqft: 1314, . . . },

{price: 275, sqft: 1200, . . . },

{price: 500, sqft: 650, . . . },

350

Page 788: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 788

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 789: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 789

{price: 700, sqft: 3000, . . . },

{price: 445, sqft: 1700, . . . },

{price: 421, sqft: 1455, . . . },

{price: 411, sqft: 1314, . . . },

{price: 275, sqft: 1200, . . . },

{price: 500, sqft: 650, . . . },

Page 790: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 790

{price: 700, sqft: 3000, . . . },

{price: 445, sqft: 1700, . . . },

{price: 421, sqft: 1455, . . . },

{price: 411, sqft: 1314, . . . },

{price: 275, sqft: 1200, . . . },

{price: 500, sqft: 650, . . . },

Page 791: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 791

{price: 700, sqft: 3000, . . . },

{price: 445, sqft: 1700, . . . },

{price: 421, sqft: 1455, . . . },

{price: 411, sqft: 1314, . . . },

{price: 275, sqft: 1200, . . . },

{price: 500, sqft: 650, . . . },

100

Page 792: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 792

{price: 700, sqft: 3000, . . . },

{price: 445, sqft: 1700, . . . },

{price: 421, sqft: 1455, . . . },

{price: 411, sqft: 1314, . . . },

{price: 275, sqft: 1200, . . . },

{price: 500, sqft: 650, . . . },

230

Page 793: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 793

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 794: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 794

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 795: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 795

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 796: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 796

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 797: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 797

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 798: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 798

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 799: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 799

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 800: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 800

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 801: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 801

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 802: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 802

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 803: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 803

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 804: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 804

Page 805: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 805

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 806: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 806

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 807: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 807

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

.enter()

.append("g")

.attr("transform", "translate(10,10)");

selection.append("circle")

.attr("cx", (d,i) => { return d.price / 2; })

.attr("cy", (d,i) => { return (4000 - d.sqft)/(4000/400) ; })

.attr("r", (d,i) => { return d.br * 10 ; })

.style("fill", (d,i) => { return color(d.pets); })

.style("opacity", "0.5")

.append("svg:title").text( (d,i) => { return print(d); });

function color(pets) {

var dogs = pets.indexOf('dogs') != -1;

var cats = pets.indexOf('cats') != -1;

if (dogs) return cats ? 'purple' : 'blue' ;

else return cats ? 'red' : 'gray';

}

function print(home) {

return `$${home.price}k, ${home.sqft}sqft, ${home.br} BRs`;

}

Page 808: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 808

Page 809: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 809

Page 810: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 810

Page 811: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 811

Page 812: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 812

Page 813: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 813

Page 814: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 814

Page 815: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 815

Page 816: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 816

Page 817: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 817

Page 818: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 818

Page 819: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 819

Page 820: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 820

400

Page 821: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 821

Page 822: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 822

Page 823: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 823

Page 824: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 824

Page 825: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 825

Page 826: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 826

Page 827: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 827

Page 828: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 828

Page 829: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

var width = 400;

var height = 400;

// draw the x-axis

var xScale = d3.scaleLinear()

.domain([0, width*2])

.range([0, width]);

var xAxis = d3.axisBottom(xScale);

svg.append("g")

.attr("transform", "translate(10,410)")

.call(xAxis);

// draw the y-axis

var yScale = d3.scaleLinear()

.range([height,0]);

.domain([0, 4000]);

var yAxis = d3.axisRight(yScale);

svg.append("g").attr("transform", "translate(10, 10)")

.call(yAxis);

SD4x-3.11 829

Page 830: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy SD4x-3.11 830

Page 831: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Accessing Data with D3.js

• D3.js can easily access data on the Web that is available through RESTful APIs

SD4x-3.11 831

var values = [];

var URL = . . .

d3.json(URL, (response) => {

// populate the values from the data in

// response that comes back from request

. . .

});

// now use values with D3 functions

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

. . .

Page 832: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Accessing Data with D3.js

• D3.js can easily access data on the Web that is available through RESTful APIs

SD4x-3.11 832

var values = [];

var URL = . . .

d3.json(URL, (response) => {

// populate the values from the data in

// response that comes back from request

. . .

});

// now use values with D3 functions

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

. . .

Page 833: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Accessing Data with D3.js

• D3.js can easily access data on the Web that is available through RESTful APIs

SD4x-3.11 833

var values = [];

var URL = . . .

d3.json(URL, (response) => {

// populate the values from the data in

// response that comes back from request

. . .

});

// now use values with D3 functions

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

. . .

Page 834: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Accessing Data with D3.js

• D3.js can easily access data on the Web that is available through RESTful APIs

SD4x-3.11 834

var values = [];

var URL = . . .

d3.json(URL, (response) => {

// populate the values from the data in

// response that comes back from request

. . .

});

// now use values with D3 functions

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

. . .

Page 835: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Accessing Data with D3.js

• D3.js can easily access data on the Web that is available through RESTful APIs

SD4x-3.11 835

var values = [];

var URL = . . .

d3.json(URL, (response) => {

// populate the values from the data in

// response that comes back from request

. . .

});

// now use values with D3 functions

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

. . .

Page 836: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Accessing Data with D3.js

• D3.js can easily access data on the Web that is available through RESTful APIs

SD4x-3.11 836

var values = [];

var URL = . . .

d3.json(URL, (response) => {

// populate the values from the data in

// response that comes back from request

. . .

});

// now use values with D3 functions

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

. . .

Page 837: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Accessing Data with D3.js

• D3.js can easily access data on the Web that is available through RESTful APIs

SD4x-3.11 837

var values = [];

var URL = . . .

d3.json(URL, (response) => {

// populate the values from the data in

// response that comes back from request

. . .

});

// now use values with D3 functions

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

. . .

Page 838: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Accessing Data with D3.js

• D3.js can easily access data on the Web that is available through RESTful APIs

SD4x-3.11 838

var values = [];

var URL = . . .

d3.json(URL, (response) => {

// populate the values from the data in

// response that comes back from request

. . .

});

// now use values with D3 functions

var svg = d3.select("svg");

var selection = svg.selectAll("g")

.data(values)

. . .

Page 839: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Summary

• D3.js allows us to generate HTML and SVG elements based on data

• We can apply functions to data sets to generate graphical elements, e.g. charts

• The data used by D3.js can include objects

• You can easily access data online using D3.js functions

SD4x-3.11 839

Page 840: Video 3.1 React.js: Introduction Chris Murphy · Property of Penn Engineering, Chris Murphy Normal DOM –How it Works •When a node is updated, the browser updates (re-renders)

Property of Penn Engineering, Chris Murphy

Review: Week 3

• React

• library and framework for creating reusable, modular components

• can render themselves based on their state

• can be combined and work together

• D3.js

• library for generating HTML and SVG based on data

• ES6: more recent version of JavaScript

SD4x-3.11 840