Presentation is loading. Please wait.

Presentation is loading. Please wait.

MIT GSL 2018 week 2 | Monday ReactJS II.

Similar presentations


Presentation on theme: "MIT GSL 2018 week 2 | Monday ReactJS II."— Presentation transcript:

1 MIT GSL 2018 week 2 | Monday ReactJS II

2 Principal Aspects of React
Components Organizing a hierarchy between them Props Passing data around (uni-directionally) State Container immutability Event Triggers and handlers Forms

3 State Accessed via this.state, organized as a dictionary
Initialized in the constructor State is mutable State should be updated ONLY through `this.setState(...)` Changing state re-renders the component

4 Remember the clock example?
function tick() { const element = ( <div> <h1>Hello, world!</h1> <h2>It is {new Date().toLocaleTimeString()}.</h2> </div> ); ReactDOM.render(element, document.getElementById('root')); } setInterval(tick, 1000); //Let’s try to make the Clock component completely reusable

5 Clock - reusable through function
function Clock(props){ return( <div> <h1>Hello, world!</h1> <h2>It is {props.date.toLocaleTimeString()}.</h2> </div> );} function tick() { ReactDOM.render(<Clock date = {new Date()} />, document.getElementById('root')); } setInterval(tick, 1000); Clock should set its own interval and update itself. We can use a class to help us

6 Ideally this is all we want to write
ReactDOM.render(<Clock />, document.getElementById('root'));

7 In order to do this we need to discuss classes in javascript

8 Class In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods). Two main type of classes - functional class pattern or the prototypal pattern. The prototypal pattern is more powerful and memory-efficient, so it’s recommended to stick to it

9 Class - Syntax, Getters and Setters
class User { constructor(name, birthday) { // invokes the setter this.name = name; this.birthday = birthday } get name() { return this._name; } set name(value) { if (value.length < 4) { alert("Name is too short."); return; } this._name = value; }} Why do we use getters and setters? let user = new User("John"); alert(user.name); // John user = new User(""); // Name too short

10 Class - inheritance It is a mechanism where you can to derive a class from another class for a hierarchy of classes that share a set of attributes and methods Each class can only be derived from one other class. That class is called a superclass, or parent class. The derived class is called subclass, or child class

11 Class - inheritance Too much inheritance can be difficult to keep track of Useful for large projects when there is a need to create multiple objects of similar type

12 Class - inheritance In class example
If you wanted to create the objects: ice cream, coke, rolex, burger, spaghetti, sprite, fries, how could you use inheritance to help arrange these objects and reduce the amount of work you need to do?

13 Class - extends Used by the subclass or child class to define its relationship to its parent class

14 Class - extends class Animal { constructor(name) { this.speed = 0; this.name = name; } run(speed) { this.speed += speed; alert(`${this.name} runs with speed ${this.speed}.`); } stop() { this.speed = 0; alert(`${this.name} stopped.`); } } // Inherit from Animal class Rabbit extends Animal { hide() { alert(`${this.name} hides!`); } } let rabbit = new Rabbit("White Rabbit"); rabbit.run(5); // White Rabbit runs with speed 5. rabbit.hide(); // White Rabbit hides!

15 Class - super Used to access the methods or variables of the parent class

16 Class - super super.method(...) to call a parent method.
class Rabbit extends Animal { hide() { alert(`${this.name} hides!`); } stop() { super.stop(); // call parent stop this.hide(); // and then hide } } let rabbit = new Rabbit("White Rabbit"); rabbit.run(5); // White Rabbit runs with speed 5. rabbit.stop(); // White Rabbit stopped. White rabbit hides! Class - super super.method(...) to call a parent method. super(...) to call a parent constructor (inside child constructor only). class Animal { constructor(name) { this.speed = 0; this.name = name; } run(speed) { this.speed += speed; alert(`${this.name} runs with speed ${this.speed}.`); } stop() { this.speed = 0; alert(`${this.name} stopped.`); } }

17 Class - constructor Previous example did not have its own constructor
class Rabbit extends Animal { // generated for extending classes without own constructors constructor(...args) { super(...args); } } class Animal { constructor(name) { this.speed = 0; this.name = name; } run(speed) { this.speed += speed; alert(`${this.name} runs with speed ${this.speed}.`); } stop() { this.speed = 0; alert(`${this.name} stopped.`); } }//********************************* // Inherit from Animal class Rabbit extends Animal { hide() { alert(`${this.name} hides!`); } } let rabbit = new Rabbit("White Rabbit"); rabbit.run(5); // White Rabbit runs with speed 5. rabbit.hide(); // White Rabbit hides!

18 Class - constructor Does this work?
class Animal { constructor(name) { this.speed = 0; this.name = name; } // ... } class Rabbit extends Animal { constructor(name, earLength) { this.speed = 0; this.name = name; this.earLength = earLength; } // ... } let rabbit = new Rabbit("White Rabbit", 10); Does this work?

19 Class - constructor class Animal { constructor(name) { this.speed = 0; this.name = name; } // ... } class Rabbit extends Animal { constructor(name, earLength) { this.speed = 0; this.name = name; this.earLength = earLength; } // ... } let rabbit = new Rabbit("White Rabbit", 10); constructors in inheriting classes must call super(...), and (!) do it before using this

20 Class - constructor Now, does this work?
class Animal { constructor(name) { this.speed = 0; this.name = name; } // ... } class Rabbit extends Animal { constructor(name, earLength) { super(name); this.speed = 0; this.name = name; this.earLength = earLength; } // ... } let rabbit = new Rabbit("White Rabbit", 10); Now, does this work?

21 Class - In class example
class Person(first, last, age, gender, interests) { constructor(first, last, age, gender, interests){ this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; } function greeting() { alert('Hi! I\'m ' + this.name.first + '.'); function farewell(){ alert(this.name.first + ' has left the building. Bye for now!'); } } var person1 = new Person('Tammi', 'Smith', 17, 'female', ['music', 'skiing', 'kickboxing']);

22 Class - In class example
We want to create a Teacher class, which inherits all the members from Person, but also includes: A new property, subject — this will contain the subject the teacher teaches. An updated greeting() method, which sounds a bit more formal than the standard greeting() method — more suitable for a teacher addressing some students at school.

23 Converting a function to a class
Create an ES6 class, with the same name, that extends React.Component Add a single empty method to it called render(). Move the body of the function into the render() method. Replace props with this.props in the render() body Delete the remaining empty function declaration

24 Converting a function to a class
class Clock extends React.Component{ render(){ return( <div> <h1>Hello, world!</h1> <h2>It is {this.props.date.toLocaleTimeString()}.</h2> </div> ); } This lets us use additional features such as local state and lifecycle hooks

25 Adding a local state to a class
class Clock extends React.Component{ constructor(props){ super(props); this.state = {date: new Date()}; } render(){ return(<div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> );} Need this to add a state

26 Can now render with this
ReactDOM.render(<Clock />, document.getElementById('root')); We still need to add the update and timer functionality We need the functions componentDidMount() and componentWillUnmount() These methods are called lifecycle hooks

27 Component Mount componentDidMount(){ this.timerID = setInterval(
() => this.tick(), 1000 ); } Runs after the component output has been rendered to the DOM

28 Component Unmount componentWillUnmount(){ clearInterval(this.timerID);
} This tears down the timer

29 Add tick() function to class
this.setState({ date: new Date()}); }

30 Full class definition class Clock extends React.Component{
constructor(props){ super(props); this.state = {date: new Date()}; } componentDidMount(){ this.timerID = setInterval( () => this.tick(), 1000);} componentWillUnmount(){ clearInterval(this.timerID);} tick(){ this.setState({date: new Date()});} render(){ return(<div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> );}}

31 Class explained When <Clock /> is passed to ReactDOM.render(), the constructor of Clock is called. This is where state is initialized React the call Clock component’s render() method and mathes the DOM to clock’s render output When Clock output is inserted in the DOM, React calls the componentDidMount() lifecycle hook. Inside which the browser is asked to set up a time to call the component’s tick() method The tick() method schedules a UI update by calling setState() with an object that contains current time. Since setState has been called, react knows to call render

32 Class explained The tick() method schedules a UI update by calling setState() with an object that contains current time. Since setState has been called, react knows to call render If the Clock component is ever removed from the DOM, React calls the componentWillUnmount() lifecycle hook to stop the timer.

33 Things we should know State should be updated ONLY through `this.setState(...)` State updates may be asynchronous State updates are Merged Data flows down

34 Asynchronous state update
React may batch multiple setState() calls into a single update for performance Do not rely on their values for calculating the next state. This code may fail this.setState({ counter: this.state.counter + this.props.increment, }); //Wrong

35 Asynchronous state update
React may batch multiple setState() calls into a single update for performance Do not rely on their values for calculating the next state. This code may fail this.setState((prevState, props) => ({ counter: prevState.counter + props.increment})); //Correct this.setState(function(prevState, props) { return {counter: prevState.counter + props.increment };});

36 Any Questions on States, Components, Props in ReactJS?

37 ReactJS Project!


Download ppt "MIT GSL 2018 week 2 | Monday ReactJS II."

Similar presentations


Ads by Google