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

React with JSX

React with JSX


Last time we talked about how react works, breaking down a react application into
small components

These components render trees of elements and other components

Using createElement is a good way to see how react works

However that can be ineffective for developers, developing complex barely


readable trees of JS syntax

To go one step further we need JSX


React with JSX
JSX combines JavaScript and XML to get its name

It is a JS extension that allows the definition of react elements using a tag-based


syntax directly within JS code

Sometimes JSX is confused with HTML as they look similar

JSX is just another way of creating React elements, avoiding the need to stress
over a missing comma in a create Element call
React elements as JSX
JSX was released by facebook with React to provide concise syntax for creating
complex DOM trees with attributes

Also makes react more readable, like HTML

In JSX the type of elements is specified with a tag

The tag’s attributes represent properties

An element’s children can be added between the opening and closing tags

Other JSX elements can be added as children aswell


React elements as JSX
JSX works with components too

A component can be defined with a class name

For example passing an array of ingredients to the IngredientList as a property


with JSX
React elements as JSX
When an array is passed it needs to be surrounded with curly braces

This is called a JS expression, and must be used when passing JS values to


components as properties

Component properties will take two types:

● Either a string
● A JavaScript expression

JS expressions cna include arrays, objects, and functions


JSX tips
When you see JSX it has a striking similarity to HTML

Many of the rules result in syntax that is similar to HTML as well

But, there are a few considerations that need to be understood when working with
JSX

● Nested components
● Classname
● Javascript expressions
● Evaluation
Nested components
JSX allows components to be added as
children of other components

Or, in other words the nesting of


components

An example being an ingredient list


having ingredient nested within it
Classname
As mentioned previously class is a reserved word in JavaScript

className is used to define the class attribute instead


JavaScript Expressions
JS expressions are wrapped in curly braces and indicate where variables will be
evaluated, and their resulting values returned

Suppose you want to display the title in an element

It can be inserted using a JS expression

The variable will be evaluated and its value returned

Values of non-string types should also appear as JS expressions


Evaluation
The JS that’s between the curly braces gets evaluated

This means operations such as string concatenation or addition can/will occur

In addition functions found in JavaScript can be invoked


Mapping arrays with JSX
JSX is JavaScript
This means JSX can be incorporated directly
inside of JS functions
Like, mapping an array to JSX elements
JSX looks clean and readable, but can’t be
interpreted with a browser
All JSX must be converted into createElement
calls
Babel
A tool for converting JSX to createElement calls

Unlike languages that require compilation JS is interpreted

As the browser interprets the code the JS doesn’t need compiled, though not
every browser supports the latest JS syntax and none support JSX

To convert, or compile, cutting edge JS and JSX into something the browser can
actually interpret a tool called Babel exists
Babel
Babel is used in production at Facebook, Netflix, PayPal, Airbnb and more

There are many ways of working with Babel, the easiest being to include a link to
the Babel CDN directly in HTML

This will compile any code in script blocks that have a type “text/babel”

Babel will compile the source code on the client before running

While not the most ideal of production solutions, it’s a great to start with JSX
Babel
Recipes as JSX
JSX provides a nice, clean way to
express react elements in code

The drawback being JSX isn’t readable


by the browser

Before the code can be interpreted by


the browser it needs to be converted
from JSX into JS
Recipes as JSX
A UI can be created with these two
components

● A menu component for listing the


recipes
● A recipe component that describes
the UI for each recipe

The data is passed to the menu


component
Recipes as JSX
The elements within the Menu
component are expressed as JSX,
containing everything within an article
element

In addition a header, h1, and div.recipes


are used to describe the DOM

The value for the title property gets


displayed in the h1
Recipes as JSX
The previous can also be refashioned to utilize the spread operator

The spread operator allows things to be expanded out

It will add each field of the recipe object as a property of the Recipe component

This shortcut will provide all the properties to the recipe component

While this may be what you want, it might also be more than you want
Recipes as JSX
The Menu function can stand further
improvements as well

Utilizing object deconstruction it can be


broken down into the variables, which
can then be accessed directly
Recipes as JSX
Each recipe has a string for the name,
an array of objects for ingredients, and
the array of strings for steps

Using object destructuring the


component can be told to locally scope
those fields by name, allowing direct
access
Recipes as JSX
React Fragments
In the previous section of slides we rendered the Menu component, a parent
component that rendered the Recipe component

Two sibling components can also be rendered using a react fragment

Suppose you want to create a component for a cat that renders to the DOM at root
React fragments
The previous renders as one would hope

But what if we add a <p> tag below the <h1>?

This causes an error, “Adjacent JSX elements


must be wrapped in an enclosing tag”

It recommends the use of fragments, and based


on the slide title you can probably guess that’s
where this is going!
React fragments
React will not render two or more adjacent
or sibling elements as a component
This have to be wrapped in an enclosing
tag like <div>
This however leads to a lot of unnecessary
tags being created as wrappers otherwise
not needed
React fragments can be used instead to
mimic the behavior of a wrapper
Intro to webpack
Once you start working on “real” react projects there are a lot of questions that
need to be considered:
● How to deal with JSX and ESNExt transformations
● How to handle dependencies
● How to optimize images and css
Many different tools have emerged to aid in these, like:
● Browserify
● Gulp
● Grunt
● Prepack
Intro to webpack
Due to its features and widespread adoption webpack has emerged as one of the
leading bundling tools

In addition to the react ecosystem has matured to include tools like:

● create-react-app
● Gatsby
● Code sandbox

These tools abstract away many of the details of code compilation

Understanding how JS/react code is compiled by webpack is vital


Intro to webpack
Webpack is a modular bundler, which takes all the different files and turns them
into a single file
The main advantages of bundling are modularity and network performance
Modularity allows the breakdown of code into parts, or modules
These modules are easier to work with, especially in a team environment
Only having to load a single dependency in the browser increases the network
performance
Each script tag makes a network request, bundling allows everything to be loaded
in one
Intro to webpack
In addition to code webpack can handle:

● Code splitting
● Minification
● Feature flagging
● Hot Module Replacement (HMR)

The recipes app from earlier ahs some issues, webpack can help to alleviate them

Using a tool like webpack allows teams to work together on large-scale projects
Intro to webpack
In addition to the previous, using the webpack module bundler can add the
following benefits:

● Modularity
● Composition
● Speed
● Consistency
Creating a project
While create-react-app helps to automate the process, it’s good to understand the
basics first

We are going to go through a few steps:

● Create the project


● Break down the recipe app into components in different files
● Setup a webpack build that incorporates Babel
Creating a project
The first step is to create your directory for the project,, and enter the directory

Next, the project needs to be initialized and the package.json created with npm

● npm init -y
● npm install react react-dom serve --save
Creating a project
Next you need to create the file structure of your
applications
Within you app directory create two more directories src and
components
Within src add:
● recipes.json
Within components add:
● Recipe.js
● Instructions.js
● Ingredients.js
Break components into modules
If you recall from earlier the recipe component
is handling a lot:

● Displaying the recipe name


● Constructing the unordered ingredients
● Displaying instructions

This should be placed in the Recipes.js we just


created

Any file using JSX will need to import react at


the top
Break components into modules
That previous slide works, but that wasn’t very functional of us

And react is based on functional programming

A better solution would be to break it down into smaller, more focused function
components and compose them together

The first step would be to pull instructions out to their own component and create a
module in a separate file

Like that instructions file we made!


Break components into modules
Here we have created a new
component called Instructions

The title of the instructions and steps


will be passed to this component

This way it can be reused for anything


with instructions
Break components into modules
We can do something similar to
ingredients
As it stands now we are only displaying
ingredients names, but there is more to
it than that
The code here assumes each
ingredient has an amount,
measurement, and name
Items can be deconstructed from props
to display individually
Break components into modules
Using the Ingredient component we can
construct an IngredientList component

This can be used anytime we need to


display a list of ingredients

First we import our ingredient


component, as an array component list

Each ingredient in list is mapped to an


Ingredient
Break components into modules
Finally, our recipe file can be
reconstructed using our components

First we import the components

Now they can be used to create a


recipe component

We have broken out our slightly


complicated recipe into smaller
components
Break components into modules
We have successfully expressed the
recipe far more declaratively
This code is nice and simple, and reads
well
This shows that a recipe displays a
name, ingredient list, and steps
We have abstracted away what it
means to display ingredients and
instructions to smaller components
Break components into modules
In a similar fashion we can create a
Menu component

The key difference is it lives in its own


file

All it needs to import is the recipe


component and react
Break components into modules
With all the components in place we are
almost done!

If you recall we need both react and


react-dom to render the components

In the base src/ directory create an


index.js file
Break components into modules
The first four statements are simply
imports

Rather than loading react and


react-dom ia the script we import them
here so webpack can bundle them

All variables are local to index.js

We pass the array of recipes to menu


Break components into modules
Now that the code has been pulled apart and more functionally done, the build
process can be built

The build process will be built with webpack, and that will put everything back
together in a single file

I acknowledge the irony in the above two statements

Splitting the files out makes larger projects easier to manager on the developer
end, and makes testing easier
Creating the webpack build
In order to create a static build process with web pack, a few things need to be
installed “npm install --save webpack webpack-cli”

For our modularity to work webpack needs to know how to bundle the source code
into a single file

As of webpack 4.0.0 webpack does not require a configuration file to bundle

If there is not config file, webpack will run the defaults

Using a config file does allow for customization of the setup


Creating the webpack build
The starting file for the app we have laid out is index.js

It imports React, ReactDOM, and Menu.js

This is what the browser should run first

Wherever webpack finds an import statement it will find the associated module in
the filesystem and include it in the bundle

Index.js>Menu.js>Recipe.js> Instructions.js and IngredientList.js> Ingredients.js

Webpack will follow this import tree and include all of the necessary modules
Creating the webpack build
The traversal Webpack does going through the import tree is known as a
dependency graph

A dependency is something the app needs, like a component or library file

Each thing needed is a point on a graph, and Webpack draws the paths between
the circles

The graph is also called the bundle


Creating the webpack build
As webpack builds the bundle it also
needs to know to transform JSX to
React Elements

webpack.config.js is just another


module that exports a JS literal object
that describes the actions webpack
should take

The configuration file should be saved


to the root of the project
Creating the webpack build
Next the Babel dependencies need
installed

● babel-loader
● @babel/core

“npm install babel-loader @babel/core


--save”

The webpack config now needs a list of


loaders to run one modules
Creating the webpack build
Now, Babel needs presets to be
specified
When a preset is set Babel is told
which transformations to perform
In other words, we tell Babel to translate
our non-browser friendly code into
something the browser works with
“npm install @babel/preset-env
@babel/preset-react --save”
And create a file .babelrc
Creating the webpack build
At this stage we have a fairly react-like project ready to go

The next stage is to run webpack to ensure everything works

Webpack is run statically, typically bundles are created before the app is deployed
to a server it can be run with “npx webpack --mode development”

Webpack will succeed creating bundle, or fail and show an error

Most errors are broken imports


Loading the bundle
Now that all errors are out of the way,
we have a bundle waiting for us in /dist
This folder contains/will contain the files
we want to run on the web server
This folder is also where index.html
should be placed
AS always, including a div with the id of
root to mount the react component to
Also be sure to import the bundle in the
script tag

You might also like