reactjs

Online console to practice react: https://codesandbox.io/
Tutorial for beginners : https://www.tutorialspoint.com/reactjs/
Questions with answers: https://www.onlineinterviewquestions.com/react-js-interview-questions/
Set up instructions: https://code.visualstudio.com/docs/nodejs/reactjs-tutorial

Please also prepare from below links prior to client interview (emphasis needs to be put on specific terminologies/ keywords/ theoretical topics). 

https://www.codementor.io/blog/5-essential-reactjs-interview-questions-du1084ym1


https://www.edureka.co/blog/interview-questions/react-interview-questions/


Security vulnerabilities of web app : tools used
Code Quality : Tools Used
CICD:  Continuous integration, deployment, integration: concepts and tools used
https://stackify.com/continuous-delivery-vs-continuous-deployment-vs-continuous-integration/


Cloud – PCF (Pivotal Cloud Foundry)

Atlassian stack experience


===============================
React : A javascript library for building User Interfaces

you need to import to packages from cdn inorder to work with React
1) React : to process JSX code correctly and has the logic to create the React Components.
2) ReactDOM : all about rendering the components to the real dom.

React uses special syntax called JSX (Syntax Extension to JavaScript)
Babel preprocessor will compile JSX to normal javascript code.

JSX Represents Objects
Babel compiles JSX down to React.createElement() calls.

These two examples are identical:
const element = (
  <h1 className="greeting">
Hello, world!
  </h1>
);
const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);
React.createElement() performs a few checks to help you write bug-free code but essentially it creates an object like this:
// Note: this structure is simplified
const element = {
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, world!'
  }
};

ReactDOM.render() # this method will allows us to render a javascript function as component to real dom

------------------------------------------
#index.js
// normal javascript function that will be treated as component with JSX syntax
function Person(props){ // here you can use any name instead of props
<div className="person"> // here class attribute will not work, you should use className in camel case
<p> Name : {props.name} </p> // to render the property name you should use single curly braces
<p> Age : {props.age} </p>
</div>
}
// the above javascript function will be rendered as a component to real dom, where div id is p1
ReactDOM.render(<Person name="Naresh" age="29"/>, document.querySelector("#p1"));

# index.html
// here the component will be rendered
<div id="p1"></div>

-----------

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function Person(propsq) {
  return (
    <div className="App">
      <h1>Hello {propsq.name}</h1>
      <h2>Start editing to see {propsq.age} some magic happen!</h2>
    </div>
  );
}

let app =  (
  <div>
    <Person name="naresh" age="25" />
    <Person name="suresh" age="29" />
  </div>
);

const rootElement = document.getElementById("root");
ReactDOM.render(app, rootElement);

===========================
#Radium module for inline styles like hover and media queries

popular package allows to use inline styles with sudo elements and media queries
npm install --save radium
//import Radium package into class based component/functional component aswell
import Radium from 'radium';
// export as below
export default Radium(Person);

when you are using media queries you need wrap the main module return jfx code in <StyleRoot> element
1) import Radium, { StyleRoot } from 'radium';

2) <StyleRoot>
<div className='App'>
...
</div>
   </StyleRoot>
=========================== 
CSS Modules - for scoped css files that will not bleed out to other components

CSS Modules allows the scoping of CSS by automatically creating a unique classname of the format [filename]\_[classname]\_\_[hash].

run npm eject # it will give the webpack configuration, this can't be reverted

edit webpack.config.js and update below part

{
  test: cssRegex,
  exclude: cssModuleRegex,
  use: getStyleLoaders({
      importLoaders: 1,
      modules: true,
      localIdentName: '[name]__[local]__[hash:base64:5]'
  }),
}

CSS Modules are a relatively new concept (you can dive super-deep into them here: https://github.com/css-modules/css-modules). With CSS modules, you can write normal CSS code and make sure, that it only applies to a given component.

It's not using magic for that, instead it'll simply automatically generate unique CSS class names for you. And by importing a JS object and assigning classes from there, you use these dynamically generated, unique names. So the imported JS object simply exposes some properties which hold the generated CSS class names as values.

Example:

In Post.css File

.Post {
    color: red;
}
In Post Component File

import classes from './Post.css';

const post = () => (
    <div className={classes.Post}>...</div>
);
Here, classes.Post  refers to an automatically generated Post  property on the imported classes  object. That property will in the end simply hold a value like Post__Post__ah5_1 .

So your .Post  class was automatically transformed to a different class (Post__Post__ah5_1 ) which is unique across the application. You also can't use it accidentally in other components because you don't know the generated string! You can only access it through the classes  object. And if you import the CSS file (in the same way) in another component, the classes  object there will hold a Post  property which yields a different (!) CSS class name. Hence it's scoped to a given component.

By the way, if you somehow also want to define a global (i.e. un-transformed) CSS class in such a .css  file, you can prefix the selector with :global .

Example:

:global .Post { ... }

Now you can use className="Post"  anywhere in your app and receive that styling.

other approach without ejecting the project
--------------------------
CSS Modules let you use the same CSS class name in different files without worrying about naming clashes. Learn more about CSS Modules here.

Button.module.css
.error {
  background-color: red;
}
another-stylesheet.css
.error {
  color: red;
}
Button.js
import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet

class Button extends Component {
  render() {
    // reference as a js object
    return <button className={styles.error}>Error Button</button>;
  }
}
Result
No clashes from other .error class names

<!-- This button has red background but not red text -->
<button class="Button_error_ax7yz">Error Button</button>

This is an optional feature. Regular <link> stylesheets and CSS files are fully supported.
CSS Modules are turned on for files ending with the .module.css extension.

===============
debugging
install React developer tool for chrome, where you can see the all the app elements and data for easy debugging

ErrorBoundary component for handling Errors with custom error messages or redirect to someother page
we can create an ErrorBoundary component class and wrap the App jsx code with ErrorBoundary as a root element

https://reactjs.org/docs/error-boundaries.html
===============

stateful vs stateless components

container components called stateful components which manages the state
presenetational components will just render the html with props

=====================
Life cycle hooks

Only available in class based components

Component Lifecycle - Creation
--------------------------------
consturctor(props)
should call super(props)
do: setup state
don't: cause Side-Effects (no html calls)
static getDerivedStateFromProps(props, state)
Do: Sync state
Don't: Cause Side-Effects
render()
Prepare & Structure your JSX code
Render Child Components (same life cycle hooks will be called)
componentDidMount() #best place to make http requests
Do: Cause Side-Effects
Don't: Update State (triggers re-render)


---
when a component gets created constructor will be executed, and we need to pass props argument to the constructor, when you call constructor you should call super(props).
you can set state in costructor like this.state = {}

when we write state={} wihtout costructor, it internally creates a constructor and this.state={} will be added in the constructor behind the scene

Component Lifecycle - Update
------------------------------
static getDerivedStateFromProps(props,sate)
Do: Sync State to Props
Don't: Cause Side-Effects
shouldComponentUpdate(nextProps, nextState)
Do: Decide whether to Continue or Note
Don't: Cause Side-Effects
May cancel updating process conditionally.
always return true or false based on the requirement.
render()
Prepare & Structure your JSX code
Update Child Component Props
Same above life cycle hooks will be called while updating the components
getSnapshotBeforeUpdate(prevProps, prevState)
Do: Last minute DOM ops
Don't: Cause Side-Effects
componentDidUpdate()
Do: Cause Side-Effects (make http requests)
Don't: Update State (triggers re-render)
======================
useEffect in functional components
this is not a life cycle hook it is just a function


import React, {useEffect} from react;

useEffect(()=> {
console.log('functional comp - useEffect called');
// Http request....
setTimeout(()=> {
alert('Saved data to cloud!');
}, 1000);
}, [props.persons]); // called only when props.persons changed.
if you pass [] empy array it will only run once when functional component created

you can use as many as useEffect() as you want

-------------------
class based component when removed it will call
componentWillUnmount()
use this life cycle function to clean any connections.

in functional based components you can do the same with useEffect() by returning a function call and write the cleanup code in that function
useEffect(()=> {
console.log('functional comp - useEffect called');
// Http request....
setTimeout(()=> {
alert('Saved data to cloud!');
}, 1000);
return () => {
//some cleanup code here.
}
}, []);

-----------------------------

Optimizing functional components with React.Memo()

export default React.memo(cockpit);

-----------------------------

use PureComponents instead of shouldComponentUpdate check

import React, { PureComponent } from 'react';

class Person extends PureComponent {
// you dont need to add shouldComponentUpdate() hook
it will automatically checks for component update when state params changes
}

Using more PureComponents instead of unncessary shouldComponentUpdate checks will improve the performance.
PureComponent will only re-render when state or prop got updated, if we don't use purecomponents we need to manually check with life cycle hook shouldComponentUpdate where you return true or false by comparing nextProps.xxx !== this.props.xxx 
----------------------
hoc higher order components - wraps other components

Create Auxillory component as a Higher Order Component (HOC) to wrap the jsx code without the div or any html elements
create hoc folder and create aux.js with the below code.
// here we don't need to  import react as we are not using any JSX, also it does't contain any logic, as it is just a wrapper
const aux = props => props.children;
export default aux;

in 16.x react has built in aux component called <React.fragment>
or
import React, { Component, Fragment } from react;

return (
<Fragment>
<p>...</p>
....
</Fragment>
);

just like ng-content in angular

--------------------
withClass HOC component

import React from 'react';

const withClass = props => {
<div className={props.classes}>{props.children}</div>
};

export default withClass;
---------------------------------
for type checking for properties on functional & class based components
npm install --save prop-types
//compontent file
import PropTypes from 'prop-types'
class Person extends Component{
...
}
Person.propTypes = {
click: PropTypes.func,
name: PropTypes.string,
age: PropTypes.number
};
--------------------------------
Using Refs

to get reference of an input element simply add ref attribute on the input element as shown below
<input ref={(inputElRef)=> {this.inputElementRef = inputElRef}} type="text"/>
//ref will execute a function which will get a reference param and we assign it to a property, with this property we can manage the input element. like below;
componentDidMount(){
this.inputElementRef.focus();
}
#React 16.3 you can create reference as below;
constructor(prop){
super(prop);
this.inputElRef = React.createRef(); // holds access to the ref property which will be assigned to the input
}
<input type="text" ref={inputElRef}/>
componentDidMount(){
this.inputElRef.current.focus();
}
#in functional components you can use useRef React Hook
import React, {useRef} from 'react';
const inputElRef = useRef(null);
<input type="text" ref={inputElRef}/>

------------------------
#Passing props around

using the Context API

create a folder context/auth-context.js
import React from 'react';
const authContext = React.createContext({authenticated: false, login: ()=>{}});
export default authContext;

in the component file import auth-context
import AuthContext from '../context/auth-context';

all the parts of the application that needs this authcontext should be wrapped by this context
<AuthContext.Provider value={{authenticated: this.state.authenticated, login: this.loginHandler}}>
<Person .../>
<Cockpit .../>
</AuthContext.Provider>

how to access the auth-context in Person component
import AuthContext from '../../context/auth-context';

in the JSX code
<AuthContext.Consumer>
{(context) => context.authenticated ? <p>Authenticated</p> : <p>Please login!</p>}}
</AuthContext.Consumer>


in class based components you can use an alternative way to use the context
to get the context not only in JSX code we may need it in other life cycle hooks, to get the context outside of the JSX

static contextType = AuthContext;
componentDidMount(){
this.inputElementRef.focus();
console.log(this.context.authenticated); //this.context is given by react
}
in the JSX code you can access the context with this.context as shown below;
{this.context.authenticated ? <p>Authenticated</p> : <p>Please login!</p>}

in functional component use useContext to access the context
import React, {useContext} from 'react';
import AuthContext from '../context/auth-context';

const authContext = useContext(AuthContext);
console.log(authContext.authenticated);
--------------------------

Burger application

1) Component Tree/Component Structure
2) Application State(Data)
3) Components vs Containers
create a new project

> create-react-app myburger
> npm run eject # it will give the webpack configuration, this can't be reverted

edit config/webpack.config.js and update below part
{
  test: cssRegex,
  exclude: cssModuleRegex,
  use: getStyleLoaders({
      importLoaders: 1,
      modules: true, // add these two lines
      localIdentName: '[name]__[local]__[hash:base64:5]'
  }),
}

create components & container folder

components - dumb / presentational that don't manage states, no matter they are created by class or functional components they are using hooks
Layout
Layout.js
container - all the components that manage states should go here.

------------------

when you are adding an image in JSX, first you should import the images, because when webpack bundles the app it should know the exact path of the image otherwise it won't work.

import burgerLogo from '../../assets/burger-logo.png';

<img src={burgerLogo}/>

-----------------
axios # is a third party javascript package used for ajax requests not a react package
// Make a get request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });
 
// Make a post request
  axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

#interceptors can be added in the root index.js, so that, all the requests will be intercepted

You can intercept requests or responses before they are handled by then or catch.

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;  ##always return the config otherwise you'r blocking the request
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });
If you may need to remove an interceptor later you can.

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
You can add interceptors to a custom instance of axios.

const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

-------------------------------
Routing

npm install --save react-router react-router-dom

We installed both react-router  and react-router-dom . Technically, only react-router-dom  is required for web development. It wraps react-router  and therefore uses it as a dependency.

App.js
-------
import {BrowserRouter} from 'react-router-dom';

//wrap the JSX code in the <BrowserRouter> to work with Routes
return (
<BrowserRouter>
<div className="App">
...
</div>
</BrowserRouter>
);

// and load the Route where you want to load the page
import {Route} from 'react-router-dom';

//and in the JSX code where you want to render the page content add
<li><a href="/">Home</a></li>
<li><a href="/new-post">New Post</a></li>

<Route path="/" exact render={() => <h1>Home content</h1>} />
//to load a component
<Route path="/" exact component={Posts} />

## but this type of routing will reload like a normal web pages not like a SPA to fix this we use "Links"

import {Route, Link} from 'react-router-dom';
<li><Link to="/">Home</Link></li>
<li><Link to={{
pathname: '/new-post',
hash: '#submit',
search: '?quick-submit=true'
}}>New Post</Link></li>

The path you can use in to can be either absolute or relative.

Absolute Paths
By default, if you just enter to="/some-path"  or to="some-path" , that's an absolute path.

Absolute path means that it's always appended right after your domain. Therefore, both syntaxes (with and without leading slash) lead to example.com/some-path .

Relative Paths
Sometimes, you might want to create a relative path instead. This is especially useful, if your component is already loaded given a specific path (e.g. posts ) and you then want to append something to that existing path (so that you, for example, get /posts/new ).

If you're on a component loaded via /posts , to="new"  would lead to example.com/new , NOT example.com/posts/new .

To change this behavior, you have to find out which path you're on and add the new fragment to that existing path. You can do that with the url  property of props.match :

<Link to={props.match.url + '/new'}>  will lead to example.com/posts/new  when placing this link in a component loaded on /posts . If you'd use the same <Link>  in a component loaded via /all-posts , the link would point to /all-posts/new .

<NavLink> can be used to add active class on the currenlty loaded page. you can also set activeStyle attribute by passing styling object css

# in the pages you can get this.posts where you can find utility functions about the route

#withRouter hoc you can pass the router props like history, location, match
import withRouter from 'react-router-dom';
export default withRouter(Posts);
#passing route parameter
  <Route path="/:id" exact component={FullPost} />

<Link to={'/' + post.id}>
<Post title={post.title}/>
</Link>

#retrieve the route parameter
this.props.match.params.id

Query Params:
You can pass them easily like this:

<Link to="/my-path?start=5">Go to Start</Link>

or

<Link
    to={{
        pathname: '/my-path',
        search: '?start=5'
    }}
    >Go to Start</Link>
React router makes it easy to get access to the search string: props.location.search .

But that will only give you something like ?start=5

You probably want to get the key-value pair, without the ?  and the = . Here's a snippet which allows you to easily extract that information:

componentDidMount() {
    const query = new URLSearchParams(this.props.location.search);
    for (let param of query.entries()) {
        console.log(param); // yields ['start', '5']
    }
}
URLSearchParams  is a built-in object, shipping with vanilla JavaScript. It returns an object, which exposes the entries()  method. entries()  returns an Iterator - basically a construct which can be used in a for...of...  loop (as shown above).

When looping through query.entries() , you get arrays where the first element is the key name (e.g. start ) and the second element is the assigned value (e.g. 5 ).

Fragment:
You can pass it easily like this:

<Link to="/my-path#start-position">Go to Start</Link>

or

<Link
    to={{
        pathname: '/my-path',
        hash: 'start-position'
    }}
    >Go to Start</Link>
React router makes it easy to extract the fragment. You can simply access props.location.hash .

-----------
Route Switch - if you want to load only one route at a time use Switch, it will load only one route that matches first and it will not anlyze any other route.

<Route path="/home" exact render={() => <h1>Home content</h1>} />
<Switch>
<Route path="/new-post" component={NewPost} />
<Route path="/:id" exact component={Posts} />
</Switch>
<Route path="/contact" exact render={() => <h1>Contact content</h1>} />

----------------------------
Navigating Programatically

onClickHandler(id){
this.props.history.push('/' + id);
}

------------------------------
Redirecting the request

import {Redirect} from 'react-router-dom'

<Switch>
<Route path="/new-post" component={NewPost} />
<Route path="/:id" exact component={Posts} />
<Redirect from="/" to="/posts" /> // add redirect in Switch, 'from' attributes only works in switch
</Switch>

you can also use history.push('/posts') or history.replace('/posts') to redirect the page.

------------------------------

#working with guards - thare are no guards like in angular, we need to check if(authenticated) condition otherwise just redirect in our code

#for 404 pages
<Switch>
          < Route exact path='/' component={Login} />
          < Route exact path='/login' component={Login} />
           < Route exact path='/form' component={MyForm} />
          <Route render = {() => <h1>404 not Found</h1>} />    // here if no other route matches finally this will be executed and the output will render     
  # <Redirect to="/posts" /> // or simply you can redirect to any other component page
          </Switch>

------------------------------
Loading Routes lazily

loading entire application bundle at upfront can be bad if we have a big application with distinct feature and distinct areas in the app, user might not visit certain areas, in this case loading such components and its children upfront is bad, so we should load the component only when the user navigates to that page, this way we will have smaller upfront code that loads faster in the browser.

The technich of downloading only what you need is known as code splitting / lazy loading

Hence you only need to load the component once you need it.

for this you need to create an hoc async component and add a function wich will take a function as an argument and execute that parameter when you load this hoc component

#refer the udemy vid
React 16.6 we have Lazy loading with React Suspense, with this you can conditionally render the component in the code even if router are not setup.
and you can use in the router too.
and you can use in the router too.

more on routing https://reacttraining.com/react-router/web/guides/philosophy

-------------------

withRouter hoc to pass history/location/match properties to the child components from the route component.
// import in the child component
import { withRouter } from 'react-router-dom';
// wrap the child component in withRouter
export default withRouter(burger);

--------------------
Forms & validation

Validate.js (you may import its functionality into your React projects): https://validatejs.org/
Get more ideas about potential validation approaches: https://react.rocks/tag/Validation
Alternatives to the manual approach taken in this course:

react-validation package: https://www.npmjs.com/package/react-validation
formsy-react package: https://github.com/christianalfoni/formsy-react

--------------------
#Redux
Standalone Third Party library often used with React for managing application state.
- all about central store, where we can store entire application state.