Nothing Special   »   [go: up one dir, main page]

Babel ReactJS Element DataFlow Component State

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

ITMD 465/565

Rich Internet Applications

Lecture 11
Fall 2020 – November 4, 2020
Tonight’s Agenda
• ReactJS Introduction / Fundamentals
• Elements, Components, State, Props
• Component Lifecycle

ITMD 465/565 - Illinois Institute of Technology


2
Babel
• Babel is used to convert JSX to plain JavaScript React calls.
• Babel can also compile our ES6 to ES5
• Babel can be directly used in the browser for development purposes
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

ITMD 465/565 - Illinois Institute of Technology


<!-- Your custom script here -->
<script type="text/babel">
const getMessage = () => "Hello World";
document.getElementById('output').innerHTML = getMessage();
</script>
• Need to configure the babel presets or it won’t do anything. Typically in a .babelrc file.
• Need to load modules for the presets you want to use and then add them to the .babelrc
• https://babeljs.io/docs/setup/#installation 3
ITMD 465/565 - Illinois Institute of Technology
ReactJS
JavaScript library for building user interfaces

4
React JS
• Created at Facebook by software engineer Jordan Walke
• An early prototype in 2011 (FaxJS) shipped as a search element on Facebook. Jordan then
worked on a prototype for the hard to manage Facebook Ads which became react.
• Deployed in newsfeed in 2011 and instagram.com in 2012 after Facebook acquired them.
• Open sourced at JSConf US May 2013

ITMD 465/565 - Illinois Institute of Technology


• Used to build interactive user interfaces for applications that have frequent data changes.
• When the components internal data changes it automatically updates the markup.
• Can be used to build UI components, single page applications (SPA), and iOS, Android or UWP
when using React Native.
• https://en.wikipedia.org/wiki/React_(JavaScript_library)
• https://reactjs.org/
• https://facebook.github.io/react-native/
5
React JS
• What is React? A library for building user interfaces.
• Composition, Unidirectional Dataflow, Explicit Mutations, Just JavaScript
• You compose a user interface with components
• Component Based - Components are encapsulated chunks and manage their own state and

ITMD 465/565 - Illinois Institute of Technology


can be nested inside each other
• Component logic is all in JavaScript and there are no HTML templates used
• Data is passed to the component through properties or props with a one way data flow
• Properties or props are a set of immutable values that gets passed to the components
render function
• Components should not directly modify the values in props. Instead pass callback functions
from the parents via props.
6
React JS
• Uses a “Virtual DOM” in the background and only updates the visible DOM when needed,
including only updating the parts that need to.
• Can be used to build single page application or just components on an existing website or
web application

ITMD 465/565 - Illinois Institute of Technology


• It can be directly used in the browser in a script tag or with a bundler to package all the JS
files in one big file.
• Works well as a node js project. All modules used are typically node modules.
• There is a Create React App node package that will produce a skeleton app as a starting
point with a preconfigured build pipeline.
• https://reactjs.org/docs/installation.html
• https://reactjs.org/docs/react-api.html
7
React JS - Composition
• You compose the UI out of multiple components

<Container>
<NavBar />
<Header />

ITMD 465/565 - Illinois Institute of Technology


<DatePicker>
<Calendar />
</DatePicker>
<Footer />
</Container>

8
React JS – Unidirectional Dataflow
• In a React app data flows from parent component to child component
• Data is passed as props to the component and the props are immutable
• If a component needs to save data/state it needs to do that in itself or get that data as props
from a parent

ITMD 465/565 - Illinois Institute of Technology


• Props are added to a component as attributes of the component (in JSX) or as the second
argument to a createElement() function call
• Different than a normal JS/Jquery app that is all event driven and just listening for events
and modifying the DOM directly
• Remember Data flows down to the component and is immutable
• <HeaderComponent name=“brian” />
• If you need to pass data back up the chain you need to pass down a function to run and call
that function within the component
9
React JS – Explicit mutations
• You will explicitly change or mutate the components state to update the component
• This makes mutations explicit
• You use the setState() function to trigger this state mutation and pass it the updated state
items

ITMD 465/565 - Illinois Institute of Technology


this.setState({
name: ‘brian’,
class: ‘itmd4565’
})
Can also pass setState() a function that looks at the known good previous state
this.setState(prevState => ({
seconds: prevState.seconds + 1
}))
10
React JS - JSX
• Can use an optional JSX syntax in your JavaScript code although typically JSX is used
• JSX is a JavaScript syntax extension
• This allows us to use what looks like HTML tag syntax to render our components.
• If we don’t use JSX we need use the React.createElement() function in its place

ITMD 465/565 - Illinois Institute of Technology


• JSX allows you to evaluate JavaScript expressions in your JSX with curly brackets { }
• Custom HTML attributes are passed in but need to start with data-
• Since JSX is not supported by browsers or runtimes you need to convert it to plain JS with a
tool like babel.
• https://reactjs.org/docs/introducing-jsx.html

11
React JS – React Elements
• Fundamental object and concept in React apps
• A React element is a JavaScript object representation that describes how you would like it to
appear on the screen. This is a JavaScript representation of a DOM Node.
• Use React.createElement() to create an element

ITMD 465/565 - Illinois Institute of Technology


• All JSX will be converted to React Elements by babel

React.createElement( type, [props], [...children] )


const element = React.createElement(
‘div’,
{id: ‘button’},
‘Login Now’
)
• If you are not passing props use null, props should be an object 12
React JS – ReactDOM
• React does not provide a way to use elements in a web page by itself
• react-dom provides the DOM-specific methods that you can use to interact with the DOM in
a web page
• We use the ReactDOM.render() method to render a React element into the web DOM

ITMD 465/565 - Illinois Institute of Technology


ReactDOM.render(element, container[, callback]);
const element = <h1>Hello, world</h1>;
ReactDOM.render(
element, document.getElementById(‘app’)
);
• https://reactjs.org/docs/react-dom.html

13
React JS - Components
• A component is a function or a Class which optionally accepts input and
returns a React element.
• React components can be function based or class based
• React component names should start with a capital letter

ITMD 465/565 - Illinois Institute of Technology


• Optionally input via props are passed into the function or class
• A component always returns a React element
• How do you decide if you want to use a function or class?
• If your component needs to save any data or state within the component you need to
use a class and save the data in the components state.
• https://reactjs.org/docs/react-component.html
14
React JS – Functional Components
• Stateless functional components can be written as a simple function
function HelloHeader(props){
return (
<h1>Hello World!</h1>
);

ITMD 465/565 - Illinois Institute of Technology


}

Or

const HelloHeader = (props) => {


return (
<h1>Hello World!</h1>
);
}
ReactDOM.render(<HelloHeader />, document.getElementById(‘app’)); 15
React JS - Components
• Components should be designed as small possibility reusable elements that are added to a
react app.
• Create components as ES6 classes. There was an old deprecated syntax that used
React.createClass() instead of ES6 classes but it has been removed.

ITMD 465/565 - Illinois Institute of Technology


• The only required method in the component class is the render() function
• A basic example is below
Class HelloHeader extends React.Component {
render() {
return <h1>Hello World!</h1>;
}
}

ReactDOM.render(<HelloHeader />, document.getElementById(‘app’));


16
React JS - Components
• The same basic component is below without JSX

Class HelloHeader extends React.Component {


render() {

ITMD 465/565 - Illinois Institute of Technology


return React.createElement(‘h1’, null, ‘Hello
World!’);
}
}

https://reactjs.org/docs/react-without-jsx.html

17
React JS - Components
• Components can use other components
Class HelloHeader extends React.Component {
render() {
return <h1>Hello World!</h1>;
}
}

ITMD 465/565 - Illinois Institute of Technology


Class Page extends React.Component {
render(){
return(
<div>
<HelloHeader />
</div>
);
}
} 18
React JS – Data Flow
• Data flows from parent to child via properties and are available in the child with
this.props. And properties are immutable.
Class HelloHeader extends React.Component {
render() {
return <h1>Hello {this.props.name}</h1>;
}
}

ITMD 465/565 - Illinois Institute of Technology


Class Page extends React.Component {
render(){
return(
<div>
<HelloHeader name=’Brian’ />
</div>
);
}
}
19
React JS – Data Flow
• Inverse Data Flow – Child to Parent
• Pass a parents event handler as a property on the child then in the child call that handler to pass data
back to the parent for setting state or something else.

Class Page extends React.Component {


render(){

ITMD 465/565 - Illinois Institute of Technology


return (
<MainHeader />
<Greeting searchFunction={this.searchHandler}>Hello World!</Greeting>
<MainFooter />
);
}

searchHandler(e){
console.log(e);
}
}
20
React JS – State
• State is place we can store data in a component and change the data to see a reflection in the UI.

• It is available in the this.state object

• Must add a constructor to your class and initialize the state there.

class App extends React.Component {


constructor(props) {

ITMD 465/565 - Illinois Institute of Technology


super(props);
this.state = { header: "Header from state...", content: "Content from state..." }
}
render() {
return ( <div> <h1>{this.state.header}</h1> <h2>{this.state.content}</h2> </div> );
}
}

• Try to make the state as simple as possible and keep as many components stateless as possible. If you
have many components that need state you should make a parent component that has the state in it
and pass it down through props.
21
React JS – State
• Do not try to modify the state object directly
// Wrong
this.state.comment = ‘Hello’;

// Correct

ITMD 465/565 - Illinois Institute of Technology


this.setState( { comment: ‘Hello’ } );
Or this.setState((currentState) => { return new state});
• If you need to set state in one component from another you need to pass
handlers down to the child component that then calls setState() in the parent
that has the state object.
• The React library watches this state and when it detects changes it compares
it to the browser DOM and updates only what is necessary
• https://reactjs.org/docs/state-and-lifecycle.html 22
React JS – Lifecycle
• React class components have lifecycle events you can use.
• We will look at a few of the most important ones.
• Some older ones are marked as not safe and will be removed soon.
• https://reactjs.org/docs/react-component.html#componentdidupdate

ITMD 465/565 - Illinois Institute of Technology


• componentDidMount()
– Called immediately after the component is rendered to the DOM
– This is good for initialization that requires the DOM nodes or network request.
• componentWillUnmount()
– Called before the component is removed from the DOM
– Used to clean up timers, subscriptions, and other items to keep them from running
• conponentDidUpdate()
– Called immediately after updating occurs. Opportunity for updated network requests but
make sure they are necessary by comparing prevProps and prevState to current. 23

Demo
Lifestyle & leak example

ITMD 465/565 - Illinois Institute of Technology


24
Helpful Array Functions
• Here are a few array functions you should know. The important part here is they
work in a functional way. They do not modify the input but instead return a new
array. Map is especially helpful when outputting JSX from arrays.
• map()
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

ITMD 465/565 - Illinois Institute of Technology


• filter()
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
• reduce()
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
• concat()
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

25
React JS Resources
• https://reactjs.org/
• https://facebook.github.io/react-native/
• https://babeljs.io/
• https://tylermcginnis.com/

ITMD 465/565 - Illinois Institute of Technology


• https://webpack.js.org/
• https://learn.co/lessons/react-create-element
• https://www.tutorialspoint.com/reactjs/reactjs_state.htm
• https://ihatetomatoes.net/react-tutorial-for-beginners/
• I’ll continue to look for more

26
Assignments

ITMD 465/565 - Illinois Institute of Technology


27
Reading/Assignments
• Quiz 3 was posted today. It is due before next class.
• I will post a new Lab in the next few days. Will cover things discussed in this lecture.
• It will be a very simple lab building some simple React components
• I wanted to see what we cover tonight first

ITMD 465/565 - Illinois Institute of Technology


• Details will go out via email
• Read MDN links on slide 25 about Helpful Array Functions. You will need to be able to use
these.

28

You might also like