React §Slavomír Moroz §PV247 Styles & Resources •Need to add styles? •css-loader | sass-loader | less-loader •How do you want them to be linked? •Inline: style-loader •Separate file: extract-loader + file-loader • • •Need some pictures? •Graphics, fonts & other binary resources •file-loader | url-loader §6-bootstrap-css-setup Install bootstrap design framework •npm install --save bootstrap (in case version 4 get released, install v3 not latest) •Import bootstrap.css from node modules 1)Build – nada •npm install style-loader css-loader url-loader file-loader extract-loader --save-dev •add css and style loader to config 2) Build – nada – font icons and graphics are missing loaders •Add url-loader for bootrap glyph icons •Add some markup to app.jsx to demo styles •Build and showcase inline styles 3) Add extract-loader and file-loader for styles •Do not use publicPath option in extract loader •Add link to css file to the app.html •Show broken relative path •Add publicPath Getting started… §Learning materials that covers commit 7-TodoList-component: § •Named vs default exports • •State & lifecycle •Do Not Modify State Directly •State Updates May Be Asynchronous •State Updates are Merged •React components •Constructor() •SetState() § •Elements List & Keys • •Handling events •If calling bind annoys you, and you are using the experimental property initializer syntax, you can use property initializers to correctly bind callbacks: •Stage-X (Experimental Babel Presets) + babel-eslint parser • • • §7-TodoList-component, 8-immutable-state-class-property-initializer Import REACT, write component class, render method with “not implemented text,” showcase default vs named export Constructor with default state, items without ids Render list in render method, array.map, element key =>array index, nullable description Add button, _onAddClick function, this undefined => bind, array.push && setState Change of state triggers re-render onAdd as lambda without bind, install babel-eslint –save-dev, eslint: “^3.x”, enable stage 2 experimental features Uuid instead of index and why npm install uuid --save setState && mutable array, showcase whats wrong. Next slide Immutable §Changes made to objects and arrays by direct mutation will not be detected, and components will not re-render. § §Side effects like mutation or asynchronous behavior will cause time travel to alter behavior between steps, breaking the application. § § § § § § Immutable § Facebook notifications bug Object immutability §Cloning an object •Object.assign(target, ...sources) •var obj = { a: 1 }; var copy = Object.assign({}, obj); console.log(copy); // { a: 1 } • •Spread operator •var obj = { a: 1 }; var copy = {…obj}; console.log(copy); // { a: 1 } § §Immutable object implementations •Flow or Typescript objects / interfaces without mutation capabilities •interface IObj { readonly a: number } § •Immutable-js - immutable collections for JavaScript •Immutable-js Record – immutable objects • §8-immutable-state-class-property-initializer Install immutable.js Replace array with list, set state with previous state (function) Composing components •Components accept inputs (called "props") and return React elements describing what should appear on the screen. •Components can refer to other components in their output. •Components must return a single root element. § §Props •A component must never modify its own props - all React components must act like pure functions with respect to their props. •PropTypes - React built-in typechecking abilities. • • §https://facebook.github.io/react/docs/components-and-props.html § § § § §9-TodoListItem-component https://facebook.github.io/react/docs/components-and-props.html https://facebook.github.io/react/docs/typechecking-with-proptypes.html Create TodoListItem class component Add PropTypes.Shape for TodoItem, mention flow a typescript Render
  • item Styling components… show slide with image, talk about layout… Atomic Design, Bem, Styled components Add styles npm install --save styled-components Showcase how to write styled components Insert styles from demo, update render method + TodoList.jsx (render + styles) https://raw.githubusercontent.com/KenticoAcademy/PV247-2017/9e567e940726905f9299e7ce85906ece213998b a/DemoReactApp/src/todo-list/TodoListItem.jsx Add onDelete prop. Write onDelete handler in TodoList.jsx Immutable list delete vs filter Functional components •A.K.A Stateless components § § § § § •This function is a valid React component because it accepts a single "props" object argument with data and returns a React element. • §10-TodoListItem-functional-component Rewrite TodoListItem class to function component. Browser events & DOM attributes §Some attributes work differently in React and HTML §https://facebook.github.io/react/docs/dom-elements.html#differences-in-attributes § §SyntheticEvent •a cross-browser wrapper around the browser's native event. •works identically across all browsers. •similar interface to native event •includes stopPropagation() and preventDefault() •SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. •You cannot access the event in an asynchronous way. • § § § §11-TodoListEditedItem-component, 12-TodoItem-edit-save Download commit with TodoListEditemItem. Show basic form, editedItemId state + start / cancel edit, moved styles to separate file (shared between two components) Attributes – className, show htmlFor in TodoListEditedItem Events -prevent-default in TodoListEditedItem -Make saving work -Copy props to state to enable edit -OnChange – async setState – access event, in async call – explain why it wont work, use spread operator, must not modify props -OnSave - Copy title and desc when saving. We will need this to showcase shallow compare in pure components Lifecycle •Each component has several "lifecycle methods" that you can override to run code at particular times in the process. •Methods prefixed with will are called right before something happens •methods prefixed with did are called right after something happens • § § § § § § §https://facebook.github.io/react/docs/react-component.html#the-component-lifecycle § § §13-component-lifecycle-local-storage When to use which method -Setup browser events not supported in react -Setup timers WillReceiveProps – Load to edited item to component state if props changed WillMount – load from local storage – constructor is better componentWillUpdate save to local storage if state changed -Will not save edited item because we are mutating the existing one. Shallow compare won’t work. -Remove mutation with spread operator Pure components §shouldComponentUpdate() •The default behavior is to re-render on every state & props change •If shouldComponentUpdate() returns false, then componentWillUpdate(), render(), and componentDidUpdate() will not be invoked. • • §To improve performance you may inherit from React.PureComponent which implements shouldComponentUpdate() with a shallow prop and state comparison. •use immutable objects to facilitate fast comparisons of nested data •shallow equality check of immutable objects produces same results as deep equality check of mutable object, but it’s faster § §https://facebook.github.io/react/docs/react-api.html#react.purecomponent §https://facebook.github.io/react/docs/optimizing-performance.html#shouldcomponentupdate-in-action § § §14-pure-component Inherit from component - All is fine, we are using spread operators Refs to DOM elements §When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument. § §When to Use Refs •Managing focus, text selection, or media playback. •Calculating viewport position. •Triggering imperative animations. •Integrating with third-party DOM libraries. § § § 16.5-container-components – components/todo-list/TodoListEditedItem.jsx Children §In JSX expressions that contain both an opening tag and a closing tag, the content between those tags is passed as a special prop: props.children. § § § § § § § § §https://facebook.github.io/react/docs/jsx-in-depth.html#children-in-jsx §Demo example – React Transition Group §15-react-css-transition npm install react-transition-group –save Transition – adds classnames based on transition state TransitionGroup– detects mount / unmounts in children and triggers transitions Higher order components §A higher-order component (HOC) is an advanced technique in React for reusing component logic. § §Concretely, a higher-order component is a function that takes a component and returns a new component. § §HOC composes the original component by wrapping it in a container component. § § § § §Demo example – React-dnd §16-HoC-react-dnd Container components •idea of separating presentation markup from logic in react components • • • • • • • • • §Presentational and Container components §Container components §16.5-container-components Presentational Components Container Components Purpose How things look (markup, styles) How things work (data fetching, state updates) To read data Read data from props Subscribe to state To change data Invoke callbacks from props Set state Debug §React dev tools •lets you inspect the React component hierarchy, including component props and state. • §Component display name •The displayName string is used in debugging messages. •babel-plugin-add-react-displayname •Automatically detects and sets displayName for React components. •babel-plugin-styled-components •adds the components' name and displayName to the class name attached to the DOM node •