REACT
REACT
REACT
-> If you have npx and Node.js installed, you can create a React application
by using create-react-app.
-> A new browser window will pop up with your newly created React App! If
not, open your browser and type localhost:3000 in the address bar.
npm installation:
npm start
Modify the React Application:
Look in the my-react-app directory, and you will find a src folder. Inside the src
folder there is a file called App.js, open it and it will look like this:
/myReactApp/src/App.js:
Example,
Replace all the content inside the <div className="App"> with a <h1>
element.
function App() {
return (
<div className="App">
<h1>Hello World!</h1>
</div>
);
}
export default App;
If you want to follow the same steps on your computer, start by stripping down
the src folder to only contain one file: index.js. You should also remove any
unnecessary lines of code inside the index.js file to make them look like the
example in the "Show React" tool below:
index.js:
React ES6:
React uses ES6, and you should be familiar with some of the new features
like:
Classes
Arrow Functions
Variables (let, const, var)
Array Methods like .map()
Destructuring
Modules
Ternary Operator
Spread Operator
Example,
class Car{
constructor(name){
this.brand=name;
}
}
Example:
<!DOCTYPE html>
<html>
<body>
<script>
class Car {
constructor(name) {
this.brand = name;
}
}
document.write(mycar.brand);
</script>
</body>
</html>
Method in Classes -
class Car {
constructor(name) {
this.brand = name;
}
present() {
return 'I have a ' + this.brand;
}}
const mycar = new Car("Ford");
mycar.present();
Class Inheritance:
A class created with a class inheritance inherits all the methods from another class
Example
Create a class named "Model" which will inherit the methods from the "Car"
class:
class Car {
constructor(name) {
this.brand = name;
}
present() {
return 'I have a ' + this.brand;
}}
class Model extends Car {
constructor(name, mod) {
super(name);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model
}}const mycar = new Model("Ford", "Mustang");
mycar.show();
By calling the super() method in the constructor method, we call the parent's
constructor method and gets access to the parent's properties and methods.
Arrow Functions:
Before:
hello=function( ) {
return “Hello World”;
}
hello=(val)=>”Hello”+val;
Infact if u have only one parameter you can skip the parantheses as well,
hello=val=> “Hello”+val;
In regular functions the this keyword represented the object that called the
function, which could be the window, the document, a button or whatever.
With arrow functions, the this keyword always represents the object that
defined the arrow function.
With a regular function, this represents the object that called the function:
class Header {
constructor() {
this.color = "Red";
}
//Regular function:
changeColor = function() {
document.getElementById("demo").innerHTML += this;
}}
const myheader = new Header();
//The window object calls the function:
window.addEventListener("load", myheader.changeColor);
//A button object calls the function:
document.getElementById("btn").addEventListener("click",
myheader.changeColor);
With an arrow function, this represents the Header object no matter who
called the function:
class Header {
constructor() {
this.color = "Red";
}
//Arrow function:
changeColor = () => {
document.getElementById("demo").innerHTML += this;
}}
const myheader = new Header();
Before ES6 there was only one way of defining your variables: with the var
keyword. If you did not define them, they would be assigned to the global
object. Unless you were in strict mode, then you would get an error if your
variables were undefined.
Now, with ES6, there are three ways of defining your variables: var, let, and
const.
var:
var x=5.6;
If you use var inside of a block, i.e. a for loop, the variable is still available
outside of that block.
let:
let x=5.6;
let is the block scoped version of var, and is limited to the block (or
expression) where it is defined.
If you use let inside of a block, i.e. a for loop, the variable is only available
inside of that loop.
const
const x = 5.6;
const is a variable that once it has been created, its value can never change.
Array Methods:
The .map() method allows you to run a function on each item in the array,
returning a new array as the result.
Example
->
ReactDOM.render(myList, document.getElementById('root'));
Before:
With destructuring:
If we only want the car and suv we can simply leave out the truck but keep the
comma:
const vehicles = ['mustang', 'f-150', 'expedition'];
const [car,, suv] = vehicles;
function calculate(a, b) {
const add = a + b;
const subtract = a - b;
const multiply = a * b;
const divide = a / b;
Destructuring Objects
Before:
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'}
myVehicle(vehicleOne);
// old way
function myVehicle(vehicle) {
const message = 'My ' + vehicle.type + ' is a ' + vehicle.color + ' ' +
vehicle.brand + ' ' + vehicle.model + '.';}
With destructuring:
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'}
myVehicle(vehicleOne);
function myVehicle({type, color, brand, model}) {
const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.';}
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red',
registration: {
city: 'Houston',
state: 'Texas',
country: 'USA'
}}
myVehicle(vehicleOne)
function myVehicle({ model, registration: { state } }) {
const message = 'My ' + model + ' is registered in ' + state + '.';}
The JavaScript spread operator (...) allows us to quickly copy all or part of an
existing array or object into another array or object.
<!DOCTYPE html>
<html>
<body>
<script>
document.write(numbersCombined);
</script>
</body>
</html>
Example
Assign the first and second items from numbers to variables and put the rest
in an array:
Example
const myVehicle = {
brand: 'Ford',
model: 'Mustang',
color: 'red'}
const updateMyVehicle = {
type: 'car',
year: 2021,
color: 'yellow'}
const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}
Modules
JavaScript modules allow you to break up your code into separate files.
This makes it easier to maintain the code-base.
Export
Let us create a file named person.js, and fill it with the things we want to
export.
Named Exports
You can create named exports two ways. In-line individually, or all at once at
the bottom.
In-line individually:
person.js
person.js
Default Exports
Let us create another file, named message.js, and use it for demonstrating
default export.
Example
message.js
Import
You can import modules into a file in two ways, based on if they are named
exports or default exports.
Before:
if (authenticated) {
renderApp();} else {
renderLogin();}
With Ternary
The purpose of the function is to display the specified HTML code inside the
specified HTML element.
There is another folder in the root directory of your React project, named
"public". In this folder, there is an index.html file.
You'll notice a single <div> in the body of this file. This is where our React
application will be rendered.
Example
ReactDOM.render(<p>Hello</p>, document.getElementById('root'));
<body>
<div id="root"></div></body>
The root node is the HTML element where you want to display the result.
It does NOT have to be a <div> element and it does NOT have to have the
id='root':
Example
<body>
<header id="sandy"></header>
</body>
ReactDOM.render(<p>Hallo</p>, document.getElementById('sandy'));
React JSX:
What is JSX?
Coding JSX
JSX allows us to write HTML elements in JavaScript and place them in the
DOM without any createElement() and/or appendChild() methods.
You are not required to use JSX, but JSX makes it easier to write React
applications.
Here are two examples. The first uses JSX and the second does not:
JSX:
Without JSX:
Expressions in JSX:
With JSX you can write expressions inside curly braces { }.
Example
Example
const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>);
So if you like to write two paragraphs, you must put them inside a parent
element, like a div element.
Example
const myElement = (
<div>
<p>I am a paragraph.</p>
<p>I am a paragraph too.</p>
</div>);
JSX will throw an error if the HTML is not correct, or if the HTML misses a
parent element.
Alternatively, you can use a "fragment" to wrap multiple lines. This will prevent
unnecessarily adding extra nodes to the DOM.
A fragment looks like an empty HTML tag: <></>.
Example
const myElement = (
<>
<p>I am a paragraph.</p>
<p>I am a paragraph too.</p>
</>);
JSX follows XML rules, and therefore HTML elements must be properly
closed.
Example
The class attribute is a much used attribute in HTML, but since JSX is
rendered as JavaScript, and the class keyword is a reserved word in
JavaScript, you are not allowed to use it in JSX.
Example
Conditions - if statements
Example
Option 2:
Example
const x = 5;
const myElement = <h1>{(x) < 10 ? "Hello" : "Goodbye"}</h1>;
React Components:
Components are independent and reusable bits of code. They serve the same
purpose as JavaScript functions, but work in isolation and return HTML.
When creating a React component, the component's name MUST start with
an upper case letter.
Class Component:
The component also requires a render() method, this method returns HTML.
Example
Function Component:
Here is the same example as above, but created using a Function component
instead.
A Function component also returns HTML, and behaves much the same way
as a Class component, but Function components can be written using much
less code, are easier to understand, and will be preferred in this tutorial.
Example
function Car() {
return <h2>Hi, I am a Car!</h2>;}
Rendering a Component
Now your React application has a component called Car, which returns an
<h2> element.
Example
Props
Example
Use an attribute to pass a color to the Car component, and use it in the
render() function:
function Car(props) {
return <h2>I am a {props.color} Car!</h2>;}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car color="red"/>);
Components in Components
Example
function Car() {
return <h2>I am a Car!</h2>;}
function Garage() {
return (
<>
<h1>Who lives in my Garage?</h1>
<Car />
</>
);}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
Components in Files
To do that, create a new file with a .js file extension and put the code inside it:
Example
This is the new file, we named it "Car.js":
function Car() {
return <h2>Hi, I am a Car!</h2>;}
export default Car;
To be able to use the Car component, you have to import the file in your
application.
Example
Now we import the "Car.js" file in the application, and we can use the Car
component as if it was created here.