0% found this document useful (0 votes)
94 views

React Js

- React allows developers to create user interfaces by defining hierarchical React components composed of nested elements. - A React app begins with a root React element that is rendered to the DOM using ReactDOM, and additional elements can be nested within this root element to build out the UI hierarchy. - Data can be mapped to React elements by using array methods like map() to iterate over data and generate the corresponding UI elements, allowing the creation of dynamic and data-driven UIs in React.

Uploaded by

ramanagopal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views

React Js

- React allows developers to create user interfaces by defining hierarchical React components composed of nested elements. - A React app begins with a root React element that is rendered to the DOM using ReactDOM, and additional elements can be nested within this root element to build out the UI hierarchy. - Data can be mapped to React elements by using array methods like map() to iterate over data and generate the corresponding UI elements, allowing the creation of dynamic and data-driven UIs in React.

Uploaded by

ramanagopal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

Click to edit Master title style

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

Annex: Modular applications


Full Materials Online
Click to edit Master title style
• You can get full materials for this course online
• http://olsensoft.com/react

• 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

• React allows you to create apps for:


• Web browsers (we'll cover this)
• iOS and Android native apps (via React Native)
Characteristics of React
Click to edit Master title style
• React is a relatively small library
• E.g. much smaller and simpler than Angular

• React is very lean and flexible - it allows you to use


your own libraries to do things like:
• Call Rest services
• Generate CSS stylesheets
• Etc.
Tooling Up
Click to edit Master title style
• You can use any IDE you like to develop React apps
• E.g. Visual Studio Code
• E.g. JetBrains WebStorm
• E.g. React Studio (primarily for graphics designers)

• Most browsers also include handy extensions, to help you


view React elements in your web page
• E.g. React Developer Tools for Chrome
• E.g. React Developer Tools for Firefox
React uses ECMAScript 6 or Above
Click to edit Master title style
• React applications are written in ECMAScript 6 or above,
which offers many key language improvements:
• Interpolated strings
• Arrow functions (a.k.a. lambdas)
• Classes and inheritance
• Object and array destructuring
• Spread parameters
• Array mapping and filtering
Managing React Packages
Click to edit Master title style
• React has quite a small number of libraries
• You need to manage these libraries in your application
• E.g. using Node Package Manager (npm) or Yarn

• To get started, we'll download React libraries directly


from https://unpkg.com/
• This is the CDN site for Node Package Manager libraries
Click to edit Master title style
Summary

• 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

1. Creating a simple app


2. Creating many elements
3. Data-driven UIs
Section 1: Creating a Simple App
Click to edit Master title style
• Scenario
• Defining an HTML target element
• Including React libraries
• The virtual DOM
• Creating React elements
• Rendering React elements
• Viewing the React virtual DOM
Scenario
Click to edit Master title style
• In this chapter we show how to create simple React
apps in pure React, using ES6++ language features

• See the Demos/02-WebApp folder


• The first example we'll look at is helloReact.html
• This is a minimalistic "Hello World" React app J
Defining an HTML Target Element
Click to edit Master title style
• A React web app has a single top-level HTML element
into which React will render the UI

• You typically define it like this


<div id="root"></div>

• 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

• The following code downloads these libraries directly:


<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

• Note the current version of React is 18


• As of April 2022
The Virtual DOM
Click to edit Master title style
• In a web app, you can manipulate elements using DOM
• Create elements, append child element, etc.
• Low-level, tedious, and quite slow rendering

• React introduces the concept of the virtual DOM


• You create React elements (lightweight JS objects)
• You manipulate these lightweight JS objects
• React renders the appropriate HTML very efficiently
Creating React Elements
Click to edit Master title style
• You can create a React element programmatically
by calling React.createElement()
• 1st argument specifies the type of element to create
• 2nd argument specifies the element's properties
• 3rd argument specifies the element's children
<script>
const obj = React.createElement(
'h1',
{id: 'my-msg', 'title': 'This is my message'},
'Hello React!'
)
</script>
Rendering React Elements
Click to edit Master title style
• Render your top-level React element into a target
location on the web page, as follows:
<script>

const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(obj)

</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

• Actually that's an important point…


• You only ever render the root React element to the DOM
Hierarchy of React Elements
Click to edit Master title style
• createElement() can take a variadic list of child
elements, so you can create a hierarchy of elements
const ul = React.createElement('ul', null,
React.createElement('li', null, 'Item1'),
React.createElement('li', null, 'Item2'),
React.createElement('li', null, 'Item3'))

• For an example, see multipleElements.html


View the Page in the Browser
Click to edit Master title style
View the Virtual DOM (1 of 2)
Click to edit Master title style
• To view components in the virtual DOM, e.g. using
React Developer Tools in Chrome:
• Show the DevTools window (F12)
• Click the Components tab
• In the Search window, click the Settings icon
• In the popup window, select the Components tab
• Deselect the "Hide components where" option
• You should now see a list of the components
View the Virtual DOM (2 of 2)
Click to edit Master title style

Note the children property


Section 3: Data-Driven UIs
Click to edit Master title style
• Overview
• Defining data
• Mapping data to elements
• Example
• View the page in the browser
Overview
Click to edit Master title style
• The previous section created a hard-coded
hierarchy of React elements

• In a real app, you'll adopt a data-driven approach


• The elements you create will depend on data
• We'll see how to create a data-driven UI in this section
• See multipleElementsViaData.html
Defining Data
Click to edit Master title style
• We'll have an array of products and an array of
shops
const products = [
'Swansea City shirt',
'Cardiff City shirt',

]

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)
)

• map() takes a lambda parameter


• The lambda receives 2 args - (array item, index)
• The lambda creates and returns a React element
Example (1 of 2)
Click to edit Master title style
• Let's map products array into an <li> collection
let prodList = React.createElement(
'ul',
null,
products.map((p, i) => React.createElement('li', {key: i}, p))
)

• Also map shops array into an <li> collection


let shopList = React.createElement(
'ul',
null,
shops.map((s, i) => React.createElement('li', {key: i}, s))
)
Example (2 of 2)
Click to edit Master title style
• Now let's put it all together
const retailer = React.createElement('div', null,
React.createElement('h1', null, 'Catalog'),
prodList,
React.createElement('h1', null, 'Shops'),
shopList
)

const root = ReactDOM.createRoot(document.getElementById('root'))


root.render(retailer)
Viewing the Page in the Browser
Click to edit Master title style
• Here's how the page looks in the browser
Click to edit Master title style
Summary

• Creating a simple app


• Creating many elements
• Data-driven UIs
Click to edit Master title style
Components

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', … … … )

const retailer = React.createElement('div', null,


React.createElement('h1', null, 'Catalog'),
prodList,
React.createElement('h1', null, 'Shops'),
shopList
)

const root = ReactDOM.createRoot(document.getElementById('root'))


root.render(retailer)

• Not feasible in a real application - too much content!


A More Modular Approach…
Click to edit Master title style
• Divide-and-conquer
• Partition the UI into a bunch of components
• Each component is responsible for one part of the UI

• Benefits of the component approach


• Each component is relatively small and focussed
• Easier to develop
• Potential reuse
• Easier to test
How to Define Components in React
Click to edit Master title style
• There are several ways to develop components in React
• Via classes and inheritance - see Section 2
• Via functional components - see Section 3

• In earlier versions or React, you could also create a


component using React.createClass()
• But this is deprecated nowadays

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

• To define your own component as a class:


• Define a class that inherits from React.Component
• Override render() to render component's elements
• Use this.props to access component's properties
Example Scenario
Click to edit Master title style
• ClassComponents.html has several components

The overall web page


is an App component

This list is an ItemsList component instance

This list is also an ItemsList component instance


Example Data
Click to edit Master title style
• Here's the familiar data for our components
const products = [
'Swansea City shirt',
'Cardiff City shirt',

]

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)
)
}
}

class ItemsList extends React.Component {


render() {
return React.createElement('ul', null,
this.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:
const app = React.createElement(App, null, null)

const root = ReactDOM.createRoot(document.getElementById('root'))


root.render(app)
Section 3: Functional Components
Click to edit Master title style
• Overview
• Functional components in our example
• Creating/rendering the App component
Overview
Click to edit Master title style
• Now we're going to see how to define components as
functional components
• This is usually simpler than defining class components
• See FunctionalComponents.html

• 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)

const root = ReactDOM.createRoot(document.getElementById('root'))


root.render(app)
Click to edit Master title style
Summary

• 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

• Elements can be HTML tags or your own components


const productsList = const basket =
<ul> <Basket>
<li>Skis</li> <Item>Skis</Item>
<li>Boots</li> <Item>Boots</Item>
</ul> </Basket>
Transpiling JSX
Click to edit Master title style
• Browsers don't understand JSX syntax
• JSX syntax must be transpiled into "pure" React

• You can use the Babel transpiler to do this


• Add a <script> to download the Babel transpiler
• Embed JSX inside <script type="text/babel">
<script src="…URL for Babel on unpkg.com…"></script>

<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>

• JSX elements can contain JS expressions in {} braces


const data = ["Swansea City shirt", "Cardiff City shirt"]

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>
)
}

const root = ReactDOM.createRoot(document.getElementById('root'))


root.render(<ItemsList/>)
Evaluating JavaScript Expressions in JSX
Click to edit Master title style
function ItemsList() { example2.html
const timestamp = new Date().toLocaleTimeString()
return (
<div>
<h1>JSX Example 2</h1>
<ul>
<li>Swansea shirt</li>
<li>Cardiff shirt</li>
<li>Lamborghini</li>
</ul>
<small>Page generated at {timestamp}</small>
</div>
)
}

const root = ReactDOM.createRoot(document.getElementById('root'))


root.render(<ItemsList/>)
Data-Driven JSX
Click to edit Master title style
const data = ["Swansea shirt", … … … ] example3.html

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>

• JSX tags must be closed


const badElem2 = <input type="text">
JSX Gotchas - 2
Click to edit Master title style
• Adjacent JSX elements must be wrapped inside an
enclosing tag
const badElem3 =
<h1>Greetings</h1>
<div>This won't work. Sorry!</div>

• To assign a CSS class, use className (not class)


const badElem4 =
<div class="emphasis">Won't work!</div>
Click to edit Master title style
Summary

• Overview of JSX
• JSX syntax
• JSX gotchas
Click to edit
Properties andMaster
State title style

1. Types for properties


2. Working with properties
3. State management
Section 1: Types for Properties
Click to edit Master title style
• Problem statement
• Solution - React property types
• How to specify property types
Problem Statement
Click to edit Master title style
• JavaScript is a dynamically typed language
• There's no "compiler" to check that you've assigned the
correct type of value to a variable
• The first you know about a type problem is when the
app crashes!

• 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

• To use these type flag, include the following script file:


https://unpkg.com/prop-types/prop-types.js
How to Specify Property Types
Click to edit Master title style
• When you define a component, specify the types for
all its properties
• How to do this depends on how you define the
component (class or functional component)

• You can specify if a property is required/optional


• You can also specify default values for the optional ones

• We'll investigate all these techniques in this chapter


Section 2: Working with Properties
Click to edit Master title style
• Properties in a class component
• Specifying property types
• Required props and defaults
• Defining a custom validator
• Properties in a functional comp
Properties in a Class Component
Click to edit Master title style
• In your class, define a static propTypes field
• Specify name and type for the component's properties
class Person extends React.Component {

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

• See example on next slide…


Defining a Custom Validator (2 of 2)
Click to edit Master title style
function isValidAge(props, propName) {

if (typeof props[propName] !== 'number')


throw new Error('Must be a number')

if (props[propName] > 120)


throw new Error('Max value is 120')
}

class Person extends React.Component {

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

• To define property types:


• Define a static propTypes field and specify prop types
• For required properties, append isRequired
• For optional properties, specify default in function sig

• To define a custom validator, it's the same as for classes


Section 3: State Management
Click to edit Master title style
• Recap component properties
• Fixed vs. mutable state
• State in a class component
• State in a functional component
• Complete examples
Recap Component Properties
Click to edit Master title style
• We've seen how to pass properties into a component
class Person extends React.Component {

render() {
const {name,age,isWelsh,skills} = this.props
return ( … some elements … )
}
} <Person name="John Evans"
age={21}
isWelsh={true}
skills={[…]} />

• (Ditto for functional components)


Fixed Properties vs. Mutable State
Click to edit Master title style
• Properties are immutable
• You can't change their values

• What if the component needs to hold mutable state?


• E.g. add items to an array, update a timestamp, etc.

• You can achieve mutable state in a component


• See following slides for details
• (Different techniques for class vs functional components)
State in a Class Component
Click to edit Master title style
• In a class component, state is available via this.state

• 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

• To modify state See example in


• Call updateFunc(newState) stateSimple2.html
Complete Examples
Click to edit Master title style
• For complete examples of state management, see:
• stateComplete1.html (class components)
• stateComplete2.html (functional components)
Click to edit Master title style
Summary

• Types for properties


• Working with properties
• State management
Click to edit
Modular Master title style
Applications

1. The need for modularity


2. Example using Webpack
Section 1: The Need for Modularity
Click to edit Master title style
• The problem
• The solution - Webpack
• Installing Webpack
• What does Webpack do?
The Problem
Click to edit Master title style
• Your web applications are likely to become quite large
• 100's or 1000's of components
• Various 3rd-party JS and CSS libraries
• Lots of versions of the above

• React introduces some additional considerations


• How do you transpile ES6 and JSX into ES5?

• How do you manage and coordinate all of this?


The Solution - Webpack
Click to edit Master title style
• Various toolsets have cropped up over the years, to
help you manage all your files and processes
• E.g. Gulp, Grunt, Browserify

• In recent years, Webpack has emerged as the


preferred tool for bundling CommonJS modules
• Node.js introduced the concept of CommonJS modules
• ES6 supports CommonJS modules too
• React apps consist of a bunch of CommonJS modules
Installing Webpack
Click to edit Master title style
• You can install webpack using npm, as follows:
npm install webpack -g
What does Webpack do?
Click to edit Master title style
• Webpack is a module bundler
• It bundles all your source files into a single file

• Benefits:
• Dramatically improves network performance
• Browser can download your app in a single HTTP request

• Additional cool capabilities in Webpack:


• Code minification, uglification, hot module replacement
Section 2: Example using Webpack
Click to edit Master title style
• Overview
• Defining a package.json file
• Installing packages
• Configuring Webpack
• App structure
• Packaging and running the app
• Another example
Overview
Click to edit Master title style
• In this section we'll take a look at a simple React app
that uses Webpack, see the following folder:
• Demo1-SimpleComponents
Defining package.json (1 of 4)
Click to edit Master title style
• package.json looks like this
• See following slides for details
{
"name": "retailersDirectory-app",
"version": "1.0.0",
"description": "Modular app via webpack",
"main": "index.js",

"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

• npm downloads specified packages and dependencies


• See the node_modules sub-folder
Configuring Webpack
Click to edit Master title style
• To configure how Webpack performs its packaging and
bundling, see webpack.config.js
• We can package app in production or development mode
• Application entry point is src/index.js
• Bundled output will be in dist/assets/bundle.js

• Babel does a lot of cool things, via "presets"


• @babel/preset-env - Compiles code to ES5
• @babel/preset-react - Compiles JSX
Application Structure
Click to edit Master title style
• dist\index.html
• Entry point for our web app as a whole
• src\index.js
• Entry point for our code
• src\components
• Defines our React components, e.g. one per file
• data
• Contains the data for our app, loaded into app on startup
Packaging and Running the Application
Click to edit Master title style
• To package and run the app:
npm start

• 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

• What's different in this example


• Uses more "interesting" data
• Contains more components
Click to edit Master title style
Summary

• The need for modularity


• Example using Webpack

You might also like