Category Archives: React

react js

Mosh React tutorial (part 1)

final source

ref – https://www.youtube.com/watch?v=Ke90Tje7VS0&t=0s&list=LLJEwHxS-Vsf-N8xSFHeMirw&index=4

Make sure you install Node to use its NPM packaging scheme. You can check the version of your node:

Set up

We first use NPM to install package create-react-app (https://www.npmjs.com/package/create-react-app)

/usr/local/bin/create-react-app -> /usr/local/lib/node_modules/create-react-app/index.js
+ create-react-app@3.4.1
added 98 packages from 46 contributors in 34.739s

In your Visual Code, go to Extensions and look for Simple React Snippets
Then install Prettier – Code formatter

Then search for Format on Save. Check it.

Creating 1st app

Now we have fully working react app..

The app would start and run on port 3000.

JSX (javascript XML)

– describe what UI will look like
– Babel – Modern javascript compiler: Babel takes JXS file, convert it to plain javascript code that browsers can understand.

It takes JXS file:

…convert it to javascript code:

React’s createElement function would then call DOM functions to create HTML Elements.

ref – babeljs.io/repl

Write React code from scratch

in src, delete all files.

In src folder, Add file index.js

babel will compile it down to a call to React.createElement.

This is why we need to import React from top.

That was the output of a JS expression. Its a React Element.
virtual DOM is a lightweight in memory representation of the DOM.
And our React Element is part of virtual DOM.

Whenever state of this object changes, React will get a new React Element, diff it with the old, and figure out what has changed.
React will then go to the real DOM, and apply those changes.

index.js

Thus, you will get “Hello World” printed with div id root.

In real world, we don’t render elements like this.
We render Components instead.

We also render tree of components, which produce complex markup.

from scratch source

First React Component

We create an basic app:

create-react-app counter-app

Now we install bootstrap. Open up a Terminal. Let’s import bootstrap into our app.

npm i bootstrap@4.1.1

index.js

After saving, when you look at the web page, you’ll see that the font has turned purple.

In our folder view, under src, create a components folder.
Inside add a new file called counter.jsx

Earlier, we have installed Simple React Snippets…let’s use that now.

imrc + tab // import react component
cc + tab // create class”

counter.jsx

Notice we’re defining the class above, and exporting it below

Now, let’s import Counter into our index.js file

Go back to your web page and you should see the text from Counter component

Embedding Expressions

add button to our Counter component

Note that JSX expressions must have 1 parent element.
JSX get compiled to React.createElement() where its argument is the type of element we want to create, i.e h1.

Thus, we must wrap what we want to display inside of an element, say a div.

counter.jsx

*Multi cursor editing – Select piece of code, press cmd + d, you’ll get multiple cursor, and change all instance in one go.

React Fragment

But let’s say you don’t like to wrap everything inside of an all encompassing element. You just want to put your fragmented code in the return expression.

Now when you look at the webpage, inspect the element, and you won’t see the div anymore.
You’ll see your html code underneath the id=root div.

Using state for dynamic data

First we override the state property in our Counter component.

We assign a property count to it.

Then in our JSX, we use curly braces and put any js expression inside of it.

save the changes, and you’ll see the results on your web page.

In between curly braces, you can write any valid javascript expression.
Hence, let’s implement a method, and use it within our curly braces.

Now, you will be able to see the string Zero when our count is 0.

We can also return JSX expression in our JS code.

JS expression like normal javascript. Pass them to a function, define const, variable…etc.

Setting Attributes

You can put set attributes via your js code as well. Let’s say we add a state property with a string to a url that generates a random image.

We put our ‘imageUrl’ property inside of the curly brace used in JSX and it will work like so:

Now, you’ll see the image in your output.

Remember that JSX gets compiled into React create element functions, which then outputs html. Hence, in our JSX, when we’re working with classes, we cannot just use class as attribute. We use ‘className’.

When we want to work with styles, we can create properties, which hold CSS data, which then changes dynamically. Those changes will be reflected in our JSX

inline styles

If you want to use inline styles, you can do another curly brace, and type in your styles like so:

Rendering Classes dynamically

We calculate bootstrap class name depending on if the count is 0 or not.
Then we render this calculation.

Thus, every time the page gets rendered, bootstrap’s “badge-warning” will be returned when the count is 0

and “badge-primary” will be returned when the count is not zero

Rendering Lists

Let’s render a list of tags.

We add new property of our state object.

JSX is NOT a TEMPLATE ENGINE, no concept of loops.

Its a simple syntax that gets compiled to React elements.

So we do it through javascript expressions via curly braces {…}

and also in our render function:

However, there is an error in the console.

Warning: Each child in an array or iterator should have a unique “key” prop.

The reason why is because it needs to uniquely identify each item in this list.
If the state of this react element changes, React needs to figure out quickly which element is changed.
And where in the DOM it needs to make changes so that it’s in sync with its virtual DOM.

Whenever you’re using the map method to render items, we need to set the ‘key’ attribute for our JSX.
Note that this key just needs to be unique in this list. It does not need to be unique in the entire application.

Conditional Rendering – use curly braces for js expressions

Let’s spit out a message for when the tags are 0.
If there is some items in the tags array, then we simply display it.

JSX is not a templating engine. We do not have if/else. To put conditional rendering, we need to go back to our javascript.

We can add a helper method i.e renderTags().

Let’s remove our ul with the tags.map and pull it out from render into function renderTags. Update your counter.jsx:

Another technique is use condition in curly braces

The first js expression is if the boolean evaluates to true, we display a string.
The second js expression executes renderTags function.

create basic React JS project

ref – https://code.visualstudio.com/docs/nodejs/reactjs-tutorial

We’ll be using the create-react-app generator for this tutorial.

Make sure you have Node.js JavaScript runtime and npm (Node.js package manager) installed.

To install the create-react-app generator, in a terminal or command prompt type:

npm install -g create-react-app

This may take a few minutes to install. You can now create a new React application by typing:

create-react-app my-app-one

This may take a few minutes to create the React application and install its dependencies.

Let’s quickly run our React application by navigating to the new folder and typing npm start to start the web server and open the application in a browser:


cd my-app-one
npm start

You should see “Welcome to React” on http://localhost:3000 in your browser. We’ll leave the web server running while we look at the application with VS Code.

To open your React application in VS Code, simply open the VS Code application and open the my-app-one folder.

Debugging React

To debug the client side React code, we’ll need to install the Debugger for Chrome extension.
Open the Extensions view and look for “Debugger for Chrome extension” in the search box. You’ll see several extensions which reference Chrome.
Press the Install button for Debugger for Chrome. The button will change to Installing then, after completing the installation, it will change to Reload. Press Reload to restart VS Code and activate the extension.

Set a breakpoint

To set a breakpoint in index.js, click on the gutter to the left of the line numbers. This will set a breakpoint which will be visible as a red circle.

Configure the Chrome debugger

We need to initially configure the debugger. To do so, go to the Debug view and click on the gear button to create a launch.json debugger configuration file. Choose Chrome from the Select Environment drop-down list. This will create a launch.json file in a new .vscode folder in your project which includes a configuration to launch the website.

We need to make one change for our example: change the port of the url from 8080 to 3000. Your launch.json should look like this:

Ensure that your development server is running (“npm start”). Then press fn+F5 or the green arrow
to launch the debugger and open a new browser instance. The source code where the breakpoint is set runs on startup before the debugger was attached so we won’t hit the breakpoint until we refresh the web page. Refresh the page and you should hit your breakpoint.

Creating React Components

https://www.kirupa.com/react/components.htm

Concept

This is terrible coding because you are doing a lot of repetitive coding.

thus, functions were created:

…and therefore, we can easily call the functions and provide parameters:

How it Works in React

Now, in React, say we want to render a bunch of h1. We have a index.html template with a given div for us to inject html content into like so:

Then, in index.js we use React’s API to render some custom html:

this repetitive usage of the h1s is the equivalent of writing the same code over and over again. Because what if we want to change them to h3. Or add bold to it. Its tiring to change it for everyone one of them. Conceptually, we want to do something similar to as how functions have solved repetitive code.

React Components

React components are reusable chunks of JavaScript that output (via JSX) HTML elements

This is where we use JSX to generate and render html to throw into a specific div. In our case, it would be the id=root div.

You create a class that extends the features of component. We do so like this:

This HelloWorld component is a component because it extends React.Component. If it didn’t do that, it would just be an empty class that doesn’t do much.

Inside our class, you can put all sorts of methods to further define what HelloWorld does.
However, there is mandatory function called Render which you must implement.

What we’ve done so far might seem crazy, but simply think of your component as a cool and new HTML tag whose functionality you fully have control over. This means you can do all sorts of HTML-ey things to it.

Properties

Our Hello component isn’t very useful because it only says Hello to one thing. It cannot say hello to other people/things. Say we want to have the Hello be applied to different names.

Just like with functions, you can pass in arguments that alter what your component does. There is a slight terminology update you need to be on top of. What we call arguments in the function world are going to be known as properties in the component world. Let’s see these properties in action!

Right now, our HelloWorld component is hard-coded to always send out Hello, world! as part of its return value. The first thing we are going to do is change that behavior by having return print out the value passed in by a property.

We are going to modify our HelloWorld component to allow you to specify who or what you greet besides the generic World.

Adding and accessing the property

We add the property by simply accessing it. If it doesn’t exist, it will be automatically added to the class. If it exists, it will access it.

The way you access a property is by referencing it via the this.props property that every component has access to. Notice how we specify this property. We place it inside curly brackets – { and }.

In JSX, if you want something to get evaluated as an expression, you need to wrap that something inside curly brackets. If you don’t do that, you’ll see the raw text this.props.greetings printed out.

Making the component call

Further example

Let’s make another component where we take an array, loop over it, and display the data. Define the component.
We add the nameArray property. Then we use the map function to look over each element in nameArray. We use parameter name and index to display the array data.

and we call the component like so:

output at localhost:3000:

Hello, Batman !!

0, Ricky
1, Vera
2, John
Hello, Superman !!

Source Code