KANNIKA LIBRETA
  • Home
  • Kotlin & Spring Boot

React

&

Angular

Picture

React

 
  • ReactJS => used for building web applications
  • React Native => used for building mobile applications

Intro

React is a frontend JavaScript framework and a library used for building UI components. It is used to build single-page applications.
Setting up a React environment (w/ create-react-app)
  • > npx create-react-app my-react-app
  • To use the latest version:> npm uninstall -g create-react-app
  • > cd my-react-app
  • > npm start
  • In browser, go to: http://localhost:3000/

OR Use React directly in HTML, by including 3 CDNs​
Using React directly in HTML code
  • <!DOCTYPE html><html><head>
  •     <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
  •     <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
  •     <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  •   </head><body>
  •     <div id="mydiv"></div>
  •     <script type="text/babel">
  •       function Hello() {
  •         return <h1>Hello World!</h1>;
  •       }
  •       ReactDOM.render(<Hello />, document.getElementById('mydiv'))
  •     </script></body></html>
React Render HTML
React renders HTML to the web page by using a function called ReactDOM.render(). The ReactDOM.render() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element.


  • src/index.js contains
​ReactDOM.render(<p>Hello KK</p>, document.getElementById('root'));
// OR
ReactDOM.createRoot(document.getElementById('root')).render(<h2>Hello KK</h2>);
  • public/index.html contains
​<body>
  <div id="root"></div>
</body>
When React renders a HTML element from src/index.js , it will be put in the "root" div element in public/index.html
JSX (JavaScript XML)     -     Allows us to write HTML directly within the JavaScript code
JSX Examples
  • With JSX

const myElement = <h1>I Love JSX!</h1>;
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);
  • Without JSX

const myElement = React.createElement('h1', {}, 'I do not use JSX!');
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);

​With JSX you can write expressions inside curly braces { }. The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result.

Example1
const myElement = <h1>React is {5 + 5} times better with JSX</h1>;
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);


Example2: To write HTML on multiple lines, put the HTML inside parentheses
const myElement = (
  <ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Cherries</li>
  </ul>
);


Example3: The HTML code must be wrapped in ONE top level element.
const myElement = (
  <>
    <p>I am a paragraph, but these paragraphs need to be one html element</p>
    <p>I am a paragraph too, which is within a fragment which look like empty html elements</p>
  </>
);


Example4: Use attribute className instead of class in JSX
const myElement = <h1 className="myclass">Hello World</h1>;

Example5: If statements
const x = 5;
let text = "Goodbye";
if (x < 10) {
  text = "Hello";
}
const myElement = <h1>{text}</h1>;
// below code uses ternary operator
const x = 5;
const myElement = <h1>{(x) < 10 ? "Hello" : "Goodbye"}</h1>;

Basics

React Component 
They serve the same purpose as JavaScript functions, but work in isolation and return HTML. Component name must start with a capital letter.

React component examples
Example1
function Fruit() {
  return <h2>Hi, I am a Fruit!</h2>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Fruit />);


Example2: props are like function arguments
function Car(props) {
  return <h2>I am a {props.color} Car!</h2>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car color="blue"/>);


Example3
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 />);


​Example4: functions from different files
  • Car.js
function Car() {
  return <h2>Hi, I am a Car!</h2>;
}
export default Car;
  • src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import Car from './Car.js';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
Life cycle of a React Component
The 3 phases are: Mounting, Updating, and Unmounting
  • Mounting: means putting elements into the DOM.
  • Updating: A component is updated whenever there is a change in the component's state or props.
  • Unmounting: when a component is removed from the DO
Class component example
Class Component
// has to include the extends React.Component statement and also requires a render() method, this method returns HTML

import React from 'react';
import ReactDOM from 'react-dom/client';

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {     // Specify the state object in the constructor method
      brand: "Lamborghini",
      model: "Aventador",
      color: "red",
      year: 2017
    };
  }
  changeColor = () => {
    this.setState({color: "blue"});  // Always use the setState() method to change the state object
  }
  // when rendering use this.state.propertyname
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
        <button
          type="button"
          onClick={this.changeColor}
        >Change color</button>
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
Props (=properties)
Props are arguments passed into React components. They are passed to components via HTML attributes. React Props are read-only! You will get an error if you try to change their value.
Props examples
Example1
function Car(props) {
  return <h2>I am a { props.brand }!</h2>;
}
function Garage() {
  return (
    <>
      <h1>Who lives in my garage?</h1>
      <Car brand="Ford" />
    </>
  );
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);


Example2
function Car(props) {
  return <h2>I am a { props.brand }!</h2>;
}
function Garage() {
  const carName = "Ford";
  return (
    <>
      <h1>Who lives in my garage?</h1>
      <Car brand={ carName } />
    </>
  );
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);


Example3
function Car(props) {
  return <h2>I am a { props.brand.model }!</h2>;
}
function Garage() {
  const carInfo = { name: "Ford", model: "Mustang" };
  return (
    <>
      <h1>Who lives in my garage?</h1>
      <Car brand={ carInfo } />
    </>
  );
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
React Events
Just like HTML DOM events, React can perform actions based on user events. React has the same events as HTML: click, change,
mouseover etc. React events are written in camelCase syntax: onClick instead of onclick. React event handlers are written inside curly braces: onClick={shoot}  instead of onClick="shoot()".
React Events Example
Example1
function Football() {
  const shoot = () => {
    alert("Great Shot!");
  }
  return (
    <button onClick={shoot}>Take the shot!</button>
    // in HTML: <button onclick="shoot()">Take the Shot!</button>
  );
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);

Example2
function Football() {
  const shoot = (a) => {
    alert(a);
  }
  return (
    <button onClick={() => shoot("Goal!")}>Take the shot!</button>
  );
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);


Example3
function Football() {
  const shoot = (a, b) => {
    alert(b.type);
/*
'b' represents the React event that triggered the function.
    In this case, the 'click' event
 output:
click
*/
  }
  return (
    <button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>
  );
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
React Conditionals example
React Conditionals

Example1: If .. else ..
function Goal(props) {
  const isGoal = props.isGoal;
  if (isGoal) {
    return <MadeGoal/>;
  }
  return <MissedGoal/>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />);


Example2: W/ Ternary Operator
function Goal(props) {
  const isGoal = props.isGoal;
  return (
    <>
      { isGoal ? <MadeGoal/> : <MissedGoal/> }
    </>
  );
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />);
React Lists
In React, you will render lists with some type of loop. The JavaScript map() array method is generally the preferred method.


Keys allow React to keep track of elements. This way, if an item is updated or removed, only that item will be re-rendered instead of the entire list. Generally, the key should be a unique ID assigned to each item.
React List example
Example
​function Car(props) {
  return <li>I am a { props.brand }</li>;
}
function Garage() {
  const cars = [
    {id: 1, brand: 'Ford'},
    {id: 2, brand: 'BMW'},
    {id: 3, brand: 'Audi'}
  ];
  return (
    <>
      <h1>Who lives in my garage?</h1>
      <ul>
        {cars.map((car) => <Car key={car.id} brand={car.brand} />)}
      </ul>
    </>
  );
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
Output:

Who lives in my garage?
  • I am a Ford
  • I am a BMW
  • I am a Audi

Hooks

You must import the Hook type that you're using from react. Hooks can ONLY be used in a React's function component and not a class component and ONLY be called at the top level.
usestate hook examples
The React useState Hook allows us to track state (of a property) in a function component.
useState accepts an initial state and returns two values:
  • The current state
  • A function that updates the state

Example1
import { useState } from "react";    // Need to import useState
import ReactDOM from "react-dom/client"; 
function FavoriteColor() {
  const [color, setColor] = useState("red");    //This is called Destructuring: assigning the return values to 2 different vars
  // const [num, setNum] = useState(9);    // You can track more than 1 property

  return (
    <>
      <h1>My favorite color is {color}!</h1>
      <button
        type="button"
        onClick={() => setColor("blue")}    // using the setColor funtion returned from useState to update the value of color
      >Blue</button>
    </>
  )
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<FavoriteColor />);

Example2: The useState Hook can be used to keep track of strings, numbers, booleans, arrays, objects, and any combination.
import { useState } from "react";
import ReactDOM from "react-dom/client";

function Car() {
  const [car, setCar] = useState({    // using useState to track an object
    brand: "Lambo",
    model: "Aventador",
    year: "2017",
    color: "blue"
  });

  const updateColor = () => {
    setCar(previousState => {    // using setCar function to only change the color - making use of JS spread operator
      return { ...previousState, color: "blue" }
    });
  }

  return (
    <>
      <h1>My {car.brand}</h1>
      <p>
        It is a {car.color} {car.model} from {car.year}.
      </p>
      <button
        type="button"
        onClick={updateColor}
      >Blue</button>
    </>
  )
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
​The useEffect Hook allows you to perform side effects in your components. ie: fetching data, directly updating the DOM, and timers.​
  • ​useEffect takes 2 arguments: useEffect(<function>, <dependency>)
    • ​1st argument: function gets executed at least once
      • ​No (2nd arg) dependency passed: useEffect(() => { //Runs on every render });
      • Empty array (as 2nd arg): useEffect(() => { //Runs only on the first render }, []);
      • Props passed (for 2nd arg): 
        • useEffect(() => { //Runs on the 1st render and any time a dependency value changes }, [prop, state]);
  • Cleaning up useEffect: useEffect(()=>{... return ...}, arg2)    // adding return statement in 1st arg can be used to cleanup
useeffect hook examples
Example1: Timer
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {    // since there's no dependency, the function gets executed for every render
    setTimeout(() => { setCount((count) => count + 1); }, 1000);    // setTimeout executes function (1st arg) after 1000ms (2nd arg)
  });
  //  useEffect(() => { setTimeout(() => { setCount((count) => count + 1); }, 1000); }, []);
  // adding empty brackets at the end will cause to execute the function only once


  return <h1>I've rendered {count} times!</h1>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Timer />);

Example2: Doubler 
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

function Counter() {
  const [count, setCount] = useState(0);
  const [calculation, setCalculation] = useState(0);

  useEffect(() => {
    setCalculation(() => count * 2);
  }, [count]); // <- add the count variable here so the function gets executed each time the value of count changes

  return (
    <>
      <p>Count: {count}</p>
      <button onClick={() => setCount((c) => c + 1)}>+</button>
      <p>Calculation: {calculation}</p>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Counter />);
React useContext is a way to manage state/property globally. It can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone.

Issue: 
State should be held by the highest parent component(function) in the stack that requires access to the state.
Usecontext hook example
Example: w/o useContext
/* without Context, we will need to pass the state as "props" through each nested component. This is called "prop drilling" */

import { useState } from "react";
import ReactDOM from "react-dom/client";

function Component1() {
  const [user, setUser] = useState("Jesse Hall");

  return (
    <>
      <h1>{`Hello ${user}!`}</h1>
      <Component2 user={user} />
    </>
  );
}

function Component2({ user }) {
  return (
    <>
      <h1>Component 2</h1>
      <Component3 user={user} />
    </>
  );
}

function Component3({ user }) {
  return (
    <>
      <h1>Component 3</h1>
      <Component4 user={user} />
    </>
  );
}

function Component4({ user }) {
  return (
    <>
      <h1>Component 4</h1>
      <Component5 user={user} />
    </>
  );
}

function Component5({ user }) {
  return (
    <>
      <h1>Component 5</h1>
      <h2>{`Hello ${user} again!`}</h2>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Component1 />);

Note: ​Even though components 2-4 did not need the state, they had to pass the state along so that it could reach component 5.
Example: w/ useContext
// Need to import useContext
import { useState, createContext, useContext } from "react";
import ReactDOM from "react-dom/client";
// Needs to be initialized
const UserContext = createContext();

function Component1() {
  const [user, setUser] = useState("Jesse Hall");

  return (   
​  /* use the Context Provider to wrap the tree of components that need the state Context. */
    <UserContext.Provider value={user}>
      <h1>{`Hello ${user}!`}</h1>
      <Component2 />
    </UserContext.Provider>
  );
}
/* Now, all components in this tree will have access to the user Context */
function Component2() {
  return (
    <>
      <h1>Component 2</h1>
      <Component3 />
    </>
  );
}

function Component3() {
  return (
    <>
      <h1>Component 3</h1>
      <Component4 />
    </>
  );
}

function Component4() {
  return (
    <>
      <h1>Component 4</h1>
      <Component5 />
    </>
  );
}

function Component5() {
  const user = useContext(UserContext);

  return (
    <>
      <h1>Component 5</h1>
      <h2>{`Hello ${user} again!`}</h2>
    </>
  );
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Component1 />);
The useRef Hook allows you to persist (continue to save) values between renders. It can be used to store a mutable value that does not cause a re-render when updated and it can be used to access a DOM element directly.
useref hook example
Example
import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const [inputValue, setInputValue] = useState("");
  const previousInputValue = useRef("");

  useEffect(() => {
​    // everytime the input value gets changed, it updates previousInputValue.current w/o causing a render
    previousInputValue.current = inputValue;    
  }, [inputValue]);

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h2>Current Value: {inputValue}</h2>
      <h2>Previous Value: {previousInputValue.current}</h2>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
The React useCallback Hook returns a memoized(=like caching values) callback function. This allows us to isolate resource intensive functions so that they will not automatically run on every render. The useCallback/useMemo Hook only runs when one of its dependencies update which can improve performance!

The useCallback and useMemo Hooks are similar. The main difference is that useMemo returns a memoized value and useCallback returns a memoized function.
usecallback & usememo hook examples
Example1: useCallback - Now the Todos component will only re-render when the todos prop changes.
index.js

import { useState, useCallback } from "react";
import ReactDOM from "react-dom/client";
import Todos from "./Todos";

const App = () => {
  const [count, setCount] = useState(0);
  const [todos, setTodos] = useState([]);

  const increment = () => {
    setCount((c) => c + 1);
  };
  const addTodo = useCallback(() => {
    setTodos((t) => [...t, "New Todo"]);
  }, [todos]);

  return (
    <>
      <Todos todos={todos} addTodo={addTodo} />
      <hr />
      <div>
        Count: {count}
        <button onClick={increment}>+</button>
      </div>
    </>
  );
};
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);


Todos.js

import { memo } from "react";

const Todos = ({ todos, addTodo }) => {
  console.log("child render");
  return (
    <>
      <h2>My Todos</h2>
      {todos.map((todo, index) => {
        return <p key={index}>{todo}</p>;
      })}
      <button onClick={addTodo}>Add Todo</button>
    </>
  );
};

export default memo(Todos);
Example2: useMemo
import { useState, useMemo } from "react";
import ReactDOM from "react-dom/client";

const App = () => {
  const [count, setCount] = useState(0);
  const [todos, setTodos] = useState([]);
  /* wrap the expensive function call with useMemo, 2nd arg is dependencies so 1st arg only gets executed when2nd arg changes val */
  const calculation = useMemo(() => expensiveCalculation(count), [count]);

  const increment = () => {
    setCount((c) => c + 1);
  };
  const addTodo = () => {
    setTodos((t) => [...t, "New Todo"]);
  };

  return (
    <div>
      <div>
        <h2>My Todos</h2>
        {todos.map((todo, index) => {
          return <p key={index}>{todo}</p>;
        })}
        <button onClick={addTodo}>Add Todo</button>
      </div>
      <hr />
      <div>
        Count: {count}
        <button onClick={increment}>+</button>
        <h2>Expensive Calculation</h2>
        {calculation}
      </div>
    </div>
  );
};

const expensiveCalculation = (num) => {
  console.log("Calculating...");
  for (let i = 0; i < 1000000000; i++) {
    num += 1;
  }
  return num;
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Hooks can also be created/custom-made. - we can define it and export from 1 file and in any other file, we can import it and use it.
React Forms
We want to try to get React to control the form. Handling forms is about how you handle the data when it changes value or gets submitted. In HTML, form data is usually handled by the DOM. In React, form data is usually handled by the components. When the data is handled by the components, all the data is stored in the component state. You can control changes by adding event handlers in the onChange attribute.
Forms examples
Example1
import { useState } from 'react';
import ReactDOM from 'react-dom/client';

function MyForm() {
  const [name, setName] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`The name you entered was: ${name}`)
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>Enter your name:
        <input 
          type="text" 
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
      <input type="submit" />
    </form>
  )
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyForm />);


Example2: 2 input fields
import { useState } from 'react';
import ReactDOM from 'react-dom/client';

function MyForm() {
  const [inputs, setInputs] = useState({});

  const handleChange = (event) => {
    const name = event.target.name;
    const value = event.target.value;
    setInputs(values => ({...values, [name]: value}))
  }

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(inputs);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>Enter your name:
      <input 
        type="text" 
        name="username" 
        value={inputs.username || ""} 
        onChange={handleChange}
      />
      </label>
      <label>Enter your age:
        <input 
          type="number" 
          name="age" 
          value={inputs.age || ""} 
          onChange={handleChange}
        />
        </label>
        <input type="submit" />
    </form>
  )
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyForm />);
/* Note: We use the same event handler function for both input fields, we could write one event handler for each, but this gives us much cleaner code and is the preferred way in React. */

Example3: Textarea 
import { useState } from 'react';
import ReactDOM from 'react-dom/client';

function MyForm() {
  const [textarea, setTextarea] = useState(
    "The content of a textarea goes in the value attribute"
  );

  const handleChange = (event) => {
    setTextarea(event.target.value)
  }

  return (
    <form>
      <textarea value={textarea} onChange={handleChange} />
    </form>
  )
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyForm />);

Example4: Select Box 
function MyForm() {
  const [myCar, setMyCar] = useState("Volvo");

  const handleChange = (event) => {
    setMyCar(event.target.value)
  }

  return (
    <form>
      <select value={myCar} onChange={handleChange}>
        <option value="Ford">Ford</option>
        <option value="Volvo">Volvo</option>
        <option value="Fiat">Fiat</option>
      </select>
    </form>
  )
}

React Router => helps with adding a Navigation bar

Create React App doesn't include page routing by default.
> cd rootDirectoryOfApp
> npm i -D react-router-dom

Page routing example
Example
  • index.js
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Layout from "./pages/Layout";
import Home from "./pages/Home";
import Blogs from "./pages/Blogs";
import Contact from "./pages/Contact";
import NoPage from "./pages/NoPage";

export default function App() {
  return (
    <BrowserRouter>    // Must wrap content first with <BrowserRouter>
      <Routes>    
        <Route path="/" element={<Layout />}>   
​        /* Renders Layout component with path "/" and this component will be shown on all pages */
          <Route index element={<Home />} />    // index attribute indicates default route
          <Route path="blogs" element={<Blogs />} />    // Contains blogs in path so it gets added to Layout: "/blogs"
          <Route path="contact" element={<Contact />} />
          <Route path="*" element={<NoPage />} />     // * path catches all undefined url paths
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
  • Layout.js
import { Outlet, Link } from "react-router-dom";   
// <Outlet> renders the current route selected and Link is used to set the URL (like <a href=".."> but for internal path)
const Layout = () => {
  return (
    <>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/blogs">Blogs</Link>
          </li>
          <li>
            <Link to="/contact">Contact</Link>
          </li>
        </ul>
      </nav>
      <Outlet />
    </>
  )
};
export default Layout;

  • Home.js
const Home = () => {
  return <h1>Home</h1>;
};
export default Home;


  • Blogs.js
const Blogs = () => {
  return <h1>Blog Articles</h1>;
};
export default Blogs;


  • Contact.js
const Contact = () => {
  return <h1>Contact Me</h1>;
};
export default Contact;


  • NoPage.js
const NoPage = () => {
  return <h1>404</h1>;
};
export default NoPage;

Styling CSS 

camelCased Property Names, ie: background-color => backgroundColor
css react example
Example1
const Header = () => {
  return (
    <>
      <h1 style={{backgroundColor: "lightblue"}}>Hello Style!</h1>
      <p>Add a little style!</p>
    </>
  );
}


Example2: creating a style object
const Header = () => {
  const myStyle = {
    color: "white",
    backgroundColor: "DodgerBlue",
    padding: "10px",
    fontFamily: "Sans-Serif"
  };
  return (
    <>
      <h1 style={myStyle}>Hello Style!</h1>
      <p>Add a little style!</p>
    </>
  );
}
Example3
  • App.cs
body {
  background-color: #282c34;
  color: white;
  padding: 40px;
  font-family: Sans-Serif;
  text-align: center;
}
  • index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './App.css';

const Header = () => {
  return (
    <>
      <h1>Hello Style!</h1>
      <p>Add a little style!.</p>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);
Scss React example
SASS is a CSS pre-processor. Sass files are executed on the server and sends CSS to the browser.
>npm i sass
Example4
  • my-sass.scss
$myColor: red;

h1 {
  color: $myColor;
}

  • index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './my-sass.scss';

const Header = () => {
  return (
    <>
      <h1>Hello Style!</h1>
      <p>Add a little style!.</p>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);
Picture

Angular

Intro

  • AngularJS = Angular v1 (not really used anymore)
  • Angular v2 and future versions are owned by Google. All versions are backward compatible

A frontend framework for building client application in HTML, CSS, and JavaScript/TypeScript. Allows to build UI with
  • testability  ;  scalability  ;  performance (responsive w/o page refresh)  ;  incorporate complex functionalities

Angular uses real DOM while React uses virtual DOM
TypeScript basics examples
TypeScript Basics

TypeScript is a language that aims at easing development of large scale applications written in JavaScript. TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project.

Mainly, 
It enables developers to add type safety to their projects.
// There are 3 basic types in TypeScript
let isDone: boolean = false;
let lines: number = 23;
let name: string = "Kannika";
// But you can omit the type annotation if the variables are derived // from explicit literals
let isDone = false;
let lines = 23;
let name = "Kannika";

// For collections, there are typed arrays and generic arrays
let list: number[] = [1, 2, 3];
// Alternatively, using the generic array type
let list: Array<number> = [1, 2, 3];

// For enumerations:
enum Color { Red, Green, Blue };
let c: Color = Color.Green; console.log(Color[c]); // "Green"

// Interfaces are structural, anything that has the properties is compliant with

interface Person {
    name: string;
    // Optional properties, marked with a "?"
    age?: number;
    // And of course functions
    move(): void;
}

// Interfaces can also describe a function type
interface SearchFunc { (source: string, subString: string): boolean; }
// Only the parameters' types are important, names are not important.
let mySearch: SearchFunc;
mySearch = function (src: string, sub: string) { return src.search(sub) != -1; }

// Tagged Union Types for modelling state that can be in one of many shapes
type State =
  
| { type: "loading" }
  | { type: "success", value: number }
  | { type: "error", message: string };
declare const state: State;
if (state.type === "success") { console.log(state.value); }
else if (state.type === "error") { console.error(state.message); }

// Template Literal Types // Use to create complex string types
type OrderSize = "regular" | "large";
type OrderItem = "Espresso" | "Cappuccino";
type Order = `A ${OrderSize} ${OrderItem}`;
let order1: Order = "A regular Cappuccino";
let order2: Order = "A large Espresso";
​let order3: Order = "A small Espresso"; // Error
Environment requirement & setup
  • Nodejs: node -v
  • Npm: npm -v
  • Installing Angular CLI: npm install -g @angular/cli ; ng version
  • IDE: Visual Studio Code
  • // Installing a specific Angular version - replace 10 with preferred version
  • npx @angular/cli@10 new my-project-name
  • // OR
  • npm uninstall -g @angular/cli
  • npm cache clean --force
  • npm install -g @angular/cli@10.0.0
  • // Updating Angular to the newest version
  • ​ng update @angular/cli @angular/core
-
  • ng new my-dream-app    // creates a new project called my-dream-app
  • cd my-dream-app
  • ng serve    // builds the app and runs it on the web server: http://localhost:4200/
-

Components

A component is like a class in Angular. It could represent a block of UI (ie: header, footer, shopping cart page, etc.). When a component is generated, it comes with
  • .html file (contains what should be displayed on the page)
  • .css file (contains the design for the HTML elements)
  • .spec.ts file (used for unit testing)
  • .ts (modules and properties are defined in here)
  • // below command will generate a new component for your project
  • $: ng g component my-new-cmp
  • The app component that is already in your project by default will always be the parent component 
index.html in src file contains a tag called: <app-root>​</app-root> => This tag calls and displays the app.component.html material. This ''app-root' name is defined and found under app.component.ts beside, select: 'app-root'
COmponent example
  • new-cmp.component.ts
import { Component, OnInit } from '@angular/core'; 

@Component({ 
   selector: 'app-new-cmp', // The name of the html tag that the parent can use to call this component's html file
   templateUrl: './new-cmp.component.html', 
   // reference to the html file created in the new component
   styleUrls: ['./new-cmp.component.css'] // reference to the style file. 
}) 
export class NewCmpComponent implements OnInit {   
   constructor() { } 
   ngOnInit() { } 
}
  • app.component.html
<!--The content below is only a placeholder and can be replaced.--> 
<div style = "text-align:center"> 
   <h1> Welcome to {{ title }}! </h1> <!-- title is variable defined in app.component.ts -->
</div>
<!-- Below tag calls and will display the html content from the app-new-cmp component -->
<app-new-cmp>​</app-new-cmp>
  • app.component.ts
import { Component } from '@angular/core';
@Component({
   selector: 'app-root', 
   templateUrl: './app.component.html', 
   styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
   title = 'Angular 7'; 
}

Modules

Modules allow you to group related components, directives, pipes, and services - to make a complex feature for your app.
for ex - user authentication, which would include login, signup, forgot password => might be separate components but they'l be grouped into one (user authentication) module

Modules example
$ ng generate module userauth
// The above command creates a folder in src called 'userauth'
// - components (that may access an api) can be placed in this module folder 
// The userauth folder will contain userauth.module.ts just like app.module.ts
// 
userauth.module.ts will contain an export statement: export class UserauthModule { }
​// We must use the above to import it in app.module.ts

$ ng generate component login    // command used to create a component (cd inside module - if needed)
// Components within modules can be used outside the module by adding this export block in userauth.module.ts
exports: [
    LoginComponent

  ]
// and in login.component.ts, beside selector, it indicates the name that we can use to create a html tag
// we can use this tag in app.component.html after the component has been exported

  • app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
​
import { UserauthModule } from './userauth/userauth.module';    // include this line to use our own created module

import { AppComponent } from './app.component';

@NgModule({
  /* All imported/generated components go under declarations */
  declarations: [
    AppComponent
  ],
  /* All imported/generated modules go under imports */
  imports: [
    BrowserModule,
    AppRoutingModule,

    UserauthModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Data Binding

It is the communication between view(app.component.html) and component class(app.component.ts). Accessing variable initialized&assigned from the component class file in the html file
Data binding example
app.component.ts
. . .
export class MyComponent{
    title = 'eShopping';
    slogan = 'Your one stop shop';
    display = false;
    funcName(){
        this.display = true;
    }
}
app.component.html

<h1>{{ title }}</h1>
<h2>{{ slogan  }}</h2>
​<button (click)="onClick()">Press me</button>
<div [hidden]="display">
    <p> Display this content </p>
</div>

Event Binding

Event binding explanation

Template

Template explanation

Directives

directives explanation

Pipes

pipes explanation

Routing

Angular routing explanation

Services

Services help when you need to use same code across all components or in every page

ng g service myservice
The above command creates 2 files myservice.service.ts and myservice.service.spec.ts
Remember to import MyserviceService in app.module.ts and add line: providers: [MyserviceService]
Write all functions and variables in myservice.service.ts within the export section 
and in app.component.ts 
. . .
temp;
constructor(private myservice: MyserviceService) {}
ngOnInit() {
    this.temp = this.myservice.varInMyservice;
​}
The above needs to be done for any other component that use the variable (like new-cmp.component.ts)

HTTP Client

Helps fetch external data and post to it.
In app.module.ts
. . .
import { HttpClientModule } from '@angular/common/http';
. . .
imports: [
    . . .,
    HttpClientModule
],
. . .
Import HttpClient in app.component.ts, create a variable that stores an api url and extract data accordingly

CLI Prompts

Name
Command
Test
ng test
Build
// for production environment
ng build --configuration=production 
​// for stating environment
ng build --configuration=staging 

Forms

Angular Forms explanation - Parts 1 & 2
Create a free web site with Weebly
  • Home
  • Kotlin & Spring Boot