11-ReactJS
11-ReactJS
Component #1 Babel
Webpack
Component #2 Babel Output
... Bundle.js
Component #N Babel
};
export default
ReactAppView;
WAPE Lecture Notes - ReactJS
<div>
<label>Name: </label>
ReactAppView render() method <input type="text" … />
<h1>Hello
{this.state.yourName}!</h1>
render() { </div>
● handleChange - this.setState({yourName:
event.target.value});
Doesn't work!
let greeting;
const en = "Hello"; const sp =
<b>Hola</b>; let {useSpanish} =
this.prop;
if (useSpanish) {greeting = sp} else
{greeting = en};
WAPE Lecture Notes - ReactJS
<div>{greeting}</div>
Iteration in JSX
● Use JavaScript array variables
let listItems = [];
for (let i = 0; i < data.length; i++) {
listItems.push(<li key={data[i]}>Data Value
{data[i]}</li>);
}
return <ul>{listItems}</ul>;
● Functional programming
<ul>{data.map((d) => <li key={d}>Data Value
{d}</li>)}</ul>
key= attribute improves efficiency ofLecture
WAPE rendering on data change
Notes - ReactJS
Styling with React/JSX - lots of different ways
Webpack can import CSS style sheets:
import React from .wape-code-name {
font-family: Courier New,
'react'; import monospace;
}
'./ReactAppView.css';
class ReactAppView extends
React.Component {
…
render() {
return (
<span
... className="wape-code-name">
Must use className= for
</ HTML class= attribute (JS
) span> keyword conflict)
;
WAPE Lecture Notes - ReactJS
Component lifecycle and methods
componentWillUnmount() { //
Shutdown timer
} clearInterval(this.timerID);
.. WAPE Lecture Notes - ReactJS
Stateless Components
● React Component can be function (not a class) if it only depends on props
function MyComponent(props) {
return <div>My name is {props.name}</div>;
}
Or using destructuring...
function MyComponent({name}) {
return <div>My name is {name}</div>;
}
● React Hooks (https://reactjs.org/docs/hooks-intro.html)
o Add state to stateless components - can do pretty much everything the class
method can WAPE Lecture Notes - ReactJS
Example React Hooks
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> Click me
</button>
</div>
);
}
WAPE Lecture Notes - ReactJS
Communicating between React components
● Passing information from parent to child: Use props (attributes)
<ChildComponent
param={infoForChildComponent} />
<ChildComponent
callback={this.parentCallback}> />