React Js
React Js
React in 4 Hours
https://olsensoft.com/react
Andy Olsen
[email protected]
Course
Click to edit Contents
Master title style
1. Getting started with React
2. Creating a React web application
3. Components
4. JSX
5. Properties and state
6. Component techniques
• What's there?
• All the slides for this course
• All the demos we're going to look at today
Click toStarted
Getting edit Master title style
with React
• What is React?
• Characteristics of React
• Tooling up
• React uses ES6 or above
• Managing React packages
What is React?
Click to edit Master title style
• React is a lightweight client-side library from
Facebook, to help you develop large-scale web apps
• Gives you a logical way to construct your UI
• Simplifies state management
• Simplifies asynchronous operations
• What is React?
• Characteristics of React
• Tooling up
• React uses ES6 or above
• Managing React packages
Click to edit
Creating Master
a React Web title
App style
• Give it a suitable id
• You'll refer to this id when you render content (see later)
Including React Libraries
Click to edit Master title style
• To use React in a web page, you need 2 libraries:
• React - Creates views
• ReactDOM - Renders views in the web browser
</script>
• ReactDOM.createRoot()
• Identifies the target location where to render content
• root.render()
• Tells React what to render
Viewing the React Virtual DOM
Click to edit Master title style
• Chrome (and other browsers) allow you to view the
React elements in the virtual DOM
• Install the React Developer Tools extension
• Then in DevTools:
• Click Components
• Select an element
Section 2: Creating Many Elements
Click to edit Master title style
• Overview
• Hierarchy of React elements
• View the page in the browser
• View the virtual DOM
Overview
Click to edit Master title style
• In this section we'll see how to create a more ambitious
virtual DOM tree, containing nested React elements
• Then we'll render the root React element to the DOM
const shops = [
'London',
'Paris',
…
]
Mapping Data to Elements
Click to edit Master title style
• You can use map() to map array item to React elem
someArray.map((arrayItem, idx) => React.createElement(htmlElem,
htmlProps,
htmlContent)
)
1. Overview
2. Class components
3. Functional components
Section 1: Overview
Click to edit Master title style
• The story so far…
• A more modular approach…
• Defining components in React
The Story So Far…
Click to edit Master title style
• The examples so far have created a monolithic
dollop of React elements in one giant block of code
let prodList = React.createElement('ul', … … … )
let shopList = React.createElement('ul', … … … )
5
Section 2: Class Components
Click to edit Master title style
• Overview
• Example scenario
• Example data
• Component classes in our example
• Creating/rendering the App component
Overview
Click to edit Master title style
• React has a class named React.Component
• Has common capabilities needed by all components
• E.g. render elements for a component
const shops = [
'London',
'Paris',
…
]
Component Classes in our Example
Click to edit Master title style
class App extends React.Component {
render() {
return React.createElement('div', null,
React.createElement('h1', null, 'Catalog'),
React.createElement(ItemsList, {items: products}, null),
React.createElement('h1', null, 'Shops'),
React.createElement(ItemsList, {items: shops}, null)
)
}
}
• A functional component:
• Is just a function (i.e. not a class)
• Receives properties as a function parameter (an object)
• Creates/returns a React element, which React will render
Components in our Example
Click to edit Master title style
function App() {
return (
React.createElement('div', null,
React.createElement('h1', null, 'Catalog'),
React.createElement(ItemsList, {items: products}, null),
React.createElement('h1', null, 'Shops'),
React.createElement(ItemsList, {items: shops}, null),
)
)
}
function ItemsList(props) {
return (
React.createElement(
"ul",
null,
props.items.map((item, i) => React.createElement("li", { key: i }, item))
)
)
}
Creating/Rendering the App Component
Click to edit Master title style
• We create/render the App component as the root
React element as follows (same as before J):
const app = React.createElement(App, null, null)
• Overview
• Class components
• Functional components
Click to edit Master title style
JSX
1. Overview of JSX
2. JSX syntax
3. JSX gotchas
Section 1: Overview of JSX
Click to edit Master title style
• The story so far…
• Introducing JSX
• Transpiling JSX
The Story So Far…
Click to edit Master title style
• In all the examples so far, we've created elements
programmatically using React.createElement()
class Retailer extends React.Component {
render() {
return React.createElement(… … …)
}
}
function Retailer(props) {
return (
React.createElement(… … …)
)
}
Introducing JSX
Click to edit Master title style
• React supports a lightweight syntax called JSX
• Create React elements concisely and directly
• Use XML to specify the elements you want to create
<script type="text/babel">
… Put your JSX code here …
</script>
Section 2: JSX Syntax
Click to edit Master title style
• JSX content
• Using JSX for components
• Simple example of JSX
• Evaluating JavaScript expressions in JSX
• Data-driven JSX
• Passing properties to a component in JSX
• Complete example
JSX Content
Click to edit Master title style
• JSX elements can contain plain text
const productsList =
<ul>
<li title="swans">Swans city shirt</li>
<li title="bloobs">Cardiff City shirt</li>
</ul>
const summaryElem =
<div>There are {data.length} items</div>
Using JSX for Components
Click to edit Master title style
function ItemsList() { example1.html
return (
<div>
<h1>JSX Example 1</h1>
<ul>
<li>Swansea shirt</li>
<li>Cardiff shirt</li>
<li>Lamborghini</li>
</ul>
</div>
)
}
function ItemsList() {
const timestamp = new Date().toLocaleTimeString()
return (
<div>
<h1>JSX Example 3</h1>
<ul>
{ data.map((item, i) => <li key={i}>{item}</li>) }
</ul>
<hr/>
<small>Page generated at {timestamp}</small>
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(<ItemsList/>)
Passing Properties to a Component in JSX
Click to edit Master title style
function ItemsList(props) { example4.html
return (
<div>
<h1>{props.heading}</h1>
<ul>
{props.items.map((item, i) => <li key={i}>{item}</li>)}
</ul>
<hr/>
<small>Page generated at {props.timestamp}</small>
</div>
)
} const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<ItemsList
heading={'JSX Example 4'}
items={data}
timestamp={new Date().toLocaleTimeString()}
/>
)
Complete Example
Click to edit Master title style
• See complete example in exercise5.html
Section 3: JSX Gotchas
Click to edit Master title style
• JSX gotchas - 1
• JSX gotchas - 2
JSX Gotchas - 1
Click to edit Master title style
• JSX is case-sensitive
const badElem1 = <SpotTheBug>oops</SpotTheBUG>
• Overview of JSX
• JSX syntax
• JSX gotchas
Click to edit
Properties andMaster
State title style
• This is unsatisfactory
• It makes your code potentially untrustworthy
• It puts a lot more pressure on your rigour during testing
The Solution - React Property Types
Click to edit Master title style
• React allows you to specify the type for properties
• React.PropTypes.number
• React.PropTypes.string
• React.PropTypes.bool
• React.PropTypes.array
• React.PropTypes.object
• React.PropTypes.func
static propTypes = {
name: PropTypes.string,
age: PropTypes.number,
isWelsh: PropTypes.bool,
propertyTypes1.html
skills: PropTypes.array
}
… propertyTypes1.html
Specifying Required Props and Defaults
Click to edit Master title style
• You can specify if a property is required
• If a property is optional, you can specify a default value
class Person extends React.Component {
static propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
isWelsh: PropTypes.bool,
skills: PropTypes.array
}
static defaultProps = {
isWelsh: false,
skills: []
}
… propertyTypes2.html
Defining a Custom Validator (1 of 2)
Click to edit Master title style
• You can define a custom validator for a property
• E.g. a regular expression pattern for postal codes
• E.g. the allowed range of values for a number
• E.g. the maximum number of elements in an array
static propTypes = {
name: PropTypes.string.isRequired,
age: isValidAge,
isWelsh: PropTypes.bool,
skills: PropTypes.array
}
…
} propertyTypes3.html
Properties in a Functional Component
Click to edit Master title style
• You can also use properties in a functional component
• See propertyTypes4.html
render() {
const {name,age,isWelsh,skills} = this.props
return ( … some elements … )
}
} <Person name="John Evans"
age={21}
isWelsh={true}
skills={[…]} />
• To initialize state:
• In the constructor, set this.state
• To access state:
• Use this.state
• To modify state:
• Call this.setState(state) See example in
stateSimple1.html
State in a Functional Component
Click to edit Master title style
• In a functional component, you use a "state hook"
• To initialize state:
• Call React.useState(initState),
• Returns [stateVariable,updateFunc]
• To access state:
• Use stateVariable
• Benefits:
• Dramatically improves network performance
• Browser can download your app in a single HTTP request
"dependencies": { … },
"devDependencies": { … },
"scripts": { … }
}
Defining package.json (2 of 4)
Click to edit Master title style
• We define the following dependencies:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
Defining package.json (3 of 4)
Click to edit Master title style
• We define the following development dependencies:
"devDependencies": {
"@babel/core": "^7.18.5",
"@babel/preset-env": "^7.18.2",
"@babel/preset-react": "^7.17.12",
"autoprefixer": "^10.4.7",
"babel-loader": "^8.2.5",
"concurrently": "^7.2.2",
"css-loader": "^6.7.1",
"opener": "^1.5.2",
"postcss-loader": "^7.0.0",
"style-loader": "^3.3.1",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0"
},
Defining package.json (4 of 4)
Click to edit Master title style
• We define the following script
• Runs webpack to package our application
• Then concurrently runs webpack and live-server
• If we edit a source file, it'll be rebundled and reloaded
"scripts": {
"start": "webpack --progress &&
concurrently
\"webpack --progress --watch\"
\"live-server dist\""
}
Installing Packages
Click to edit Master title style
• To install packages, open a command window in your
project folder, and run the following command:
npm install
• What happens:
• Builds and bundles the app (into the dist folder)
• Starts live-server
• Opens a browser and loads your home page
• If you change any file, it's rebundled and reloaded
Another Example
Click to edit Master title style
• We have another example, in the following folder
• Demo2-ComponentHierarchy