Example: tourism industry

ReactJS Introduction - Stanford University

CS142 Lecture Notes - ReactJSReactJS IntroductionMendel RosenblumCS142 Lecture Notes - ReactJSReactJS JavaScript framework for writing the web applications Like AngularJS - Snappy response from running in browser Less opinionated: only specifies rendering view and handling user interactions Uses Model-View-Controller pattern View constructed from Components using pattern Optional, but commonly used HTML templating Minimal server-side support dictated Focus on supporting for programming in the large and single page applications Modules, reusable components, testing, Lecture Notes - ReactJSReactJS Web Application Page<!doctype html> <html> <head> <title>CS142 Example</title> </head> <body> <div id="reactapp"> </div> <script src=".

CS142 Lecture Notes - ReactJS Styling with React/JSX - lots of different ways import React from 'react'; import './ReactAppView.css'; class ReactAppView extends React.Component

Tags:

  Trace, Reactjs

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Advertisement

Transcription of ReactJS Introduction - Stanford University

1 CS142 Lecture Notes - ReactJSReactJS IntroductionMendel RosenblumCS142 Lecture Notes - ReactJSReactJS JavaScript framework for writing the web applications Like AngularJS - Snappy response from running in browser Less opinionated: only specifies rendering view and handling user interactions Uses Model-View-Controller pattern View constructed from Components using pattern Optional, but commonly used HTML templating Minimal server-side support dictated Focus on supporting for programming in the large and single page applications Modules, reusable components, testing, Lecture Notes - ReactJSReactJS Web Application Page<!doctype html> <html> <head> <title>CS142 Example</title> </head> <body> <div id="reactapp"> </div> <script src=".

2 / "> </script> </body> </html> ReactJS applications come as a JavaScript blob that will use the DOM interface to write the view into the div. CS142 Lecture Notes - ReactJSReactJS tool chainBabel - Transpile language features ( ECMAS cript, JSX) to basic JavaScriptWebpack - Bundle modules and resources (CSS, images) Output loadable with single script tag in any browser Component #1 Component #2 Component # ComponentsCS142 Lecture Notes - - Render element into browser DOM import React from 'react';import ReactDOM from 'react-dom';import ReactAppView from './components/ReactAppView';let viewTree = (ReactAppView, null);let where = ('reactapp'); (viewTree, where);Renders the tree of React elements (single component named ReactAppView) into the browser's DOM at the div with id= Modules - Bring in React and web app React Lecture Notes - - ES6 class definition import React from 'react';class ReactAppView extends { constructor(props) { super(props).}}

3 } render() { .. };export default ReactAppView;Require method render() - returns React element tree of the Component's view. Inherits from props is set to the attributes passed to the component. CS142 Lecture Notes - ReactJSReactAppView render() methodrender() { let label = ('label', null,'Name: '); let input = ('input', { type: 'text', value: , onChange: (event) => (event) });let h1 = ('h1', null, 'Hello ', , '!'); return ('div', null, label, input, h1);}Returns element tree with div (label, input, and h1) elements<div> <label>Name: </label> <input type="text" .. /> <h1>Hello { }!</h1> </div>CS142 Lecture Notes - ReactJSReactAppView render() method w/o variables render() { return ('div', null, ('label', null,'Name: '), ('input', { type: 'text', value: , onChange: (event) => (event) }), ('h1', null, 'Hello ', , '!))

4 ') );}CS142 Lecture Notes - ReactJSUse JSX to generate calls to createElementrender() { return ( <div> <label>Name: </label> <input type="text" value={ }onChange={(event) => (event)} /> <h1>Hello { }!</h1> </div> );} JSX makes building tree look like templated HTML embedded in Lecture Notes - ReactJSComponent state and input handlingimport React from 'react';class ReactAppView extends { constructor(props) { super(props); = {yourName: ""}; } handleChange(event) { ({ yourName: }); } .. Input calls to setState which causes React to call render() againMake <h1>Hello { }!</h1> workCS142 Lecture Notes - ReactJSOne way binding: Type 'D' Character in input box JSX statement: <input type="text" value={ }onChange={(event) => (event)} />Triggers handleChange call with == "D" handleChange - ({yourName: }); is changed to "D" React sees state change and calls render again: Feature of React - highly efficient re-renderingCS142 Lecture Notes - ReactJSCalling React Components from events: A problemclass ReactAppView extends {.}

5 HandleChange(event) { ({ yourName: }); } ..}Understand why: <input type="text" value={ } onChange={ } />Doesn't work!CS142 Lecture Notes - ReactJSCalling React Components from events workaround Create instance function bound to instanceclass ReactAppView extends { constructor(props) { super(props); = {yourName: ""}; = (this); } handleChange(event) { ({ yourName: }); }CS142 Lecture Notes - ReactJSCalling React Components from events workaround Using public fields of classes with arrow functionsclass ReactAppView extends { constructor(props) { super(props); = {yourName: ""}; } handleChange = (event) => { ({ yourName: }); }.}

6 CS142 Lecture Notes - ReactJSCalling React Components from events workaround Using arrow functions in JSXclass ReactAppView extends { .. handleChange(event) { ({ yourName: }); } render() { return ( <input type="text" value={ }onChange={(event) => (event)} /> ); } CS142 Lecture Notes - ReactJSA digression: camelCase vs dash-caseWord separator in multiword variable name Use dashes: active-buffer-entry Capitalize first letter of each word: activeBufferEntryIssue: HTML is case-insensitive but JavaScript is 's JSX has HTML-like stuff embedded in : Use camelCase for attributesAngularJS: Used both: dashes in HTML and camelCase in JavaScript!}

7 CS142 Lecture Notes - ReactJSProgramming with JSX Need to remember: JSX maps to calls to Writing in JavaScript HTML-like syntax that is converted to JavaScript function calls (type, props, ..children); type: HTML tag ( h1, p) or props: attributes ( type="text") Uses camelCase! children: Zero or more children which can be either: String or numbers A React element An Array of the aboveCS142 Lecture Notes - ReactJSJSX templates must return a valid children param Templates can have JavaScript scope variables and expressions <div>{foo}</div> Valid if foo is in scope ( if foo would have been a valid function call parameter) <div>{foo + 'S' + computeEndingString()}</div> Valid if foo & computeEndString in scope Template must evaluate to a value <div>{if (useSpanish) {.}}

8 } }</div> - Doesn't work: if isn't an expression Same problem with "for loops" and other JavaScript statements that don't return values Leads to contorted looking JSX: Example: Anonymous immediate functions <div>{ (function() { if ..; for ..; return val;})() }</div>CS142 Lecture Notes - ReactJSConditional render in JSX Use JavaScript Ternary operator (?:)<div>{ ? <b>Hola</b> : "Hello"}</div> Use JavaScript variables let greeting;const en = "Hello"; const sp = <b>Hola</b>;let {useSpanish} = ; if (useSpanish) {greeting = sp} else {greeting = en}; <div>{greeting}</div>CS142 Lecture Notes - ReactJSIteration in JSX Use JavaScript array variableslet listItems = [];for (let i = 0; i < ; i++) { (<li key={data[i]}>Data Value {data[i]}</li>);}return <ul>{listItems}</ul>; Functional programming <ul>{ ((d) => <li key={d}>Data Value {d}</li>)}</ul>key= attribute improves efficiency of rendering on data changeCS142 Lecture Notes - ReactJSStyling with React/JSX - lots of different waysimport React from 'react';import '.

9 '; class ReactAppView extends { ..render() { return ( <span className="cs142-code-name"> .. </span> );Webpack can import CSS style sheets:.cs142-code-name { font-family: Courier New, monospace;}Must use className= for HTML class= attribute (JS keyword conflict)CS142 Lecture Notes - ReactJSComponent lifecycle and Lecture Notes - ReactJSExample of lifecycle methods - update UI every 2s class Example extends { ..componentDidMount() { // Start 2 sec counter const incFunc = () => ({ counter: + 1 }); = setInterval(incFunc, 2 * 1000);}componentWillUnmount() { // Shutdown timer clearInterval( );} ..CS142 Lecture Notes - ReactJSStateless Components React Component can be function (not a class) if it only depends on propsfunction MyComponent(props) { return <div>My name is { }</div>;}Or using MyComponent({name}) { return <div>My name is {name}</div>;} React Hooks ( ) Add state to stateless components - can do pretty much everything the class method canCS142 Lecture Notes - ReactJSExample React Hooksimport React, { useState, useEffect } from 'react';function Example() { const [count, setCount] = useState(0).}}}}

10 Return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> );}CS142 Lecture Notes - ReactJSExample React Hooks - Lifecycle exampleimport React, { useState, useEffect } from 'react';function Example() { const [count, setCount] = useState(0); useEffect(() => { = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> );}CS142 Lecture Notes - ReactJSCommunicating between React components Passing information from parent to child: Use props (attributes)<ChildComponent param={infoForChildComponent} /> Passing information from child to parent: Callbacks = (infoFromChild) => { /* processInfoFromChild */};<ChildComponent callback={ }> /> React Context ( ) Global variables for subtree of components


Related search queries