150 likes | 178 Views
Info + Web Tech Course. Web Programming. Anselm Spoerri PhD (MIT) SC&I @ Rutgers University aspoerri@rutgers.edu. Lecture 8 - Overview. Ex2 Revision Due Mar 17 Ex2 Walkthrough Screencast Make sure all expected inputs provided to Geocoding function React.js – Learn the Basics
E N D
Info + Web Tech Course • Web Programming • Anselm Spoerri PhD (MIT) • SC&I @ Rutgers University • aspoerri@rutgers.edu
Lecture 8 - Overview • Ex2 Revision Due Mar 17 • Ex2 Walkthrough Screencast • Make sure all expected inputs provided to Geocoding function • React.js – Learn the Basics • Recap • map / filter function and arrow (=>) function • Refs and Parent / Children Relationships • Update / Remove / Add Children • Component Lifecycle • Spring Break Mar 18 - 24 • Quiz 4 – React.js Due Mar 31 (moved from Mar 17) • Ex4 Due Mar 31 • What to Do BEFORE Next Class • Videos in Week 9 (in green)
Recap – React.js • Add React.js CDN files to web page (v16) https://reactjs.org/docs/cdn-links.html • ReactDOM.render( element, container, [callback] ) • React.createElement( type, [props], [...children] ) • JSX, or JavaScript as XML – write HTML tags inside JavaScript introducing-jsx • If a tag is empty, you may close it immediately with />, like XML • React DOM uses camelCase property naming convention CSS class becomes className in JSX, and tabindex becomes tabIndex. • Any JavaScript expression within curly braces { … }inside JSX • Babel.js – transpile or preprocess JSX using Babel try it : https://babeljs.io/repl/ • Code written with JSX will be converted to use React.createElement(). • Add Babel.js CDN file to web page and <script type="text/babel"> • React = Components = UI element with changing data • ES6 Class Component • class MyCompextends React.Component { render () { HTML }} • ReactDOM.render(<MyComp/>, where in DOM)) • Always start component names with capital letter
Recap – React.js • Properties • Class component: this.props contains props defined by caller of this component • {this.props.text} inside JSX <MyComp text="Hello World"/> • {this.props.children} inside JSX <MyComp text="Hi">World</myComp> • Props used to pass information between main component and subcomponents • Define state that can be queried and changed • constructor(props) { • super(props) // access this.props in constructor • this.state = { checked: false } // define state checked • this.handleCheck = this.handleCheck.bind(this) // keep this in scope • } • handleCheck () { this.setState({ checked: !this.state.checked })} • Note: if we want to use this.props inside of return ()then need to work using vars • Statesstore what is happening in application and react to state / data changes • constructor(props) { super(props) this.state = { x: y } this.funcZ = this.funcZ.bind(this)
React.js – Create React App using Node.js • Node.js https://en.wikipedia.org/wiki/Node.js • Create Fast Web Server using JS and modules • NodeJSRuntime Chrome • Server JavaScript • Event-driven programming using callbacks • Asynchronous events • Non-blockingI/O • Create React app with no build configurations • Open Command Prompt • npm –v • Install npmfrom https://nodejs.org/en/ • npminstall -g create-react-app • Make sure in ex4 folder inside of terminal • create-react-app bulletin-board • cd into the bulletin-board folder • npm start • Ctrl C to stop
React.js – Create React App using Node.js • Housekeeping • Download Lynda Exercise Files: https://www.lynda.com/ajax/course/645064/download/exercise/692567 • In bulletin-board folder, select src folder • Use: files from Exercise Files > Ch05 > 05_03> completed> bulletin-board > src • Open Command Prompt • cd into the bulletin-board folder and npm start • // npm install --save react-icons uses now v3 which is different from v2 • Need to comment out references to react-icons using // and {/* … */}
map / filter function and arrow (=>) function • array.map() • creates new array with results of calling function for every array element • https://www.w3schools.com/jsref/jsref_map.asp • array.filter() • creates new array filled with array elements that pass test (provided as function) • https://www.w3schools.com/jsref/jsref_filter.asp • arrow function • shorter syntax than a function expression and does not bind its ownthis, arguments, super, or new.target. • https://www.lynda.com/JavaScript-tutorials/Arrow-functions/424003/459181-4.html • var materials =['Hydrogen','Helium','Lithium','Beryllium']; • var materialsLength1 =materials.map(function(material){return material.length;}); • var materialsLength2 =materials.map((material)=>{return material.length;}); • var materialsLength3 =materials.map(material =>material.length);
React.js – Refs and Parent / Children Relationships • Refs store & access actual value of user input component • <textarea ref={input => this._newText = input}/> • this._newText.value • or • <textarea ref="newText"></textarea> • this.refs.newText.value • Parent / Children Relationships – Create Subcomponents • Create Main / Parent component: var Board = React Component • this.state = { notes: array with content to add to subcomponents} • render() { return (<div className='board'> • { this.state.notes.map(this.eachNote) } • </div>) } • Nest inside of board div a series of Note components with property key
React.js – Update Children • Update Children • constructor(props) for Parent Component = array of objects {id: 0, note: 'Call Bob'} • Create update method • use ... as a "spread" operator to pass whole props object (all of its properties) • https://reactjs.org/docs/jsx-in-depth.html • update(newText, id) { • this.setState(prevState => ({ • notes: prevState.notes.map( • note => (note.id !== i) ? note : {...note, note: newText} • ) • })) • <Note key={i} index={i} onChange={this.update}> {note.note} </Note> • save method for Note component needs to updated • this.props.onChange(this._newText.value, this.props.index) // passed to update func
React.js – Remove Children • Remove Children • Create remove method: only keep notes don’t have id • remove(id) { • this.setState(prevState=> ({ • notes: prevState.notes.filter(note => note.id !== id) • })) • <Note key={ note.id} id={note.id} onChange={this.update} • onRemove={this.remove}> {note.note} </Note> • remove method for Note component needs to be updated • this.props.onRemove(this.props.index)
React.js – Add Children • Add Children • this.state = { notes = [] } • add(text){ • this.setState(prevState=> ({ • notes: [ ...prevState.notes, { id: this.nextId(), note: text}] • })) • Need to add button to Board • render() { return (<div className='board'> • {this.state.notes.map(this.eachNote)} • <button onClick={this.add.bind(null, "New Note")}>+</button> • </div>) } • <style> div.note {position: relative / absolute;} </style>
React.js – Fix Bug and Ex4 Preview • Fix Bug • Can’t remove all the notes (hint: what does index represent; role of id) • Instead of <Note index={i} /> we use <Note index={note.id} /> • Ex4 Preview • Change note appearance when click on “Done” • Add comments to a note • Remove comments from a note • Study code used to add and remove notes from board
React.js – Component Lifecycle • https://reactjs.org/docs/state-and-lifecycle.html • Hooks for Creation, Lifetime and Teardown • Mounting • componentWillMount // load data or do things before DOM renders 1st time • render • componentDidMountcomponentDidMount • Updating • componentWillReceiveProps • shouldComponentUpdate • componentWillUpdate • render • componentDidUpdate • componentWillUnmount
React.js – Build Web Interface • Library for Creating Interfaces • Focus on the View • Virtual DOM= JS Object: efficiently update & render components when data changes • Components and subcomponents nested structure (like HTML) • One-way Data Flow • States store what is happening in application and react to changes in state or data • Props used to pass information between main component and subcomponents • JSX = JavaScript as XML – write HTML tags inside JavaScript • Combine the best parts of JavaScript with HTML tags • JSX needs to be converted to regular JavaScript Need Build Process • \
React.js – Build Web Interface • Complex Data • map( function (item, index) { } )to iterate through array items • index can be used to specify key • each React iteration requires individual key • this needs context map().bind(this) or use arrow function • Needs render () single element that can contain other elements • Lifecycle Methods • componentDidMount called once before render • Good place to lead external data or work with AJAX • When importing data, make sure this is bound properly • componentDidMount • Use to cancel outstanding requests • Sub-components • No access to state of parent Use props