A Must Read For ReactJS Dev

https://app.pluralsight.com/player?course=react-js-getting-started&author=samer-buna&name=react-js-getting-started-m1&clip=0&mode=live

Components are like functions, reusable and composable

Using javascript to render html makes react to have virtual Views in memory which is known as Virtual DOM.

Tree Reconciliation: React do not write the whole DOM tree every time it just writes difference between new tree and old tree.

React component are of two types

Function component, Class component.

Function Component

 

Const MyComponent = (props) => {

 Return (

 <mycompoennt />

 );}

 

Class Component

It also acts like function and receives props but it has private internal state which makes react a reactive language because when state of react component changes react automatically re-renders that component.

States can be changed where the props are all fix values, class component can only change their internal states not property values.

When we write html in Js it is actully not treated as html because it gets translated to Javascript.

Function component example:

// Write JavaScript here and press Ctrl+Enter to execute

 const Button = (props) =>

 {

 return (

 <button>5</button> 

); };

function can be written like this too

Const Button = function(props)

{

   return(<button>{props.label}</button>);

 };

 ReactDOM.render(<Button label=”Go” />, mountNode)

To implement click functionality on button so to change button value increment on click, we need to have a class component as function component cannot handle state.

Class Component

ReactDom.render(componentToRender, whereToRender)

To define state of componennt we need to write it in constructor first.

 the standard practice is to define this function in the class

This.setState is async function and theoratically we can encounter race condition. To avoid such scenario we need to update our handleClick function like this

handleClick = () => { 

this.setState((prevState)=>

 { 

     return { 

counter: prevState.counter + 1

 };

 }) };

 ReactDOM.render(<Button />, mountNode);

 

React can be written with or without jsx

To compile JSX into js we need babel js

Standard Practice is to define function in class however we can define like this too

If we need to return siblings then we can wrap them in a parent element like div as below

class Button extends React.Component

state = { counter: 0 };

 handleClick = () =>

 { this.setState((prevState)=> ({ counter: prevState.counter + 1 })) 

};

 render()

{ return(<button onClick={this.handleClick}

>{this.state.counter}</button>); } }

 class Txt extends React.Component{ render()

{ return(<input type=”text” />) } } 

class App extends React.Component{ render(){ return(<div> <Button /> <Txt /> </div>) 

} } 

ReactDOM.render(<App />, mountNode);

Let’s call the function of parent component from child component

We will now define handleClick  function in App component and Button component will invoke this function.

Class App extends React.Component{ 

render(){ return(<div>

 <Button onClickFunction=”this.handleClick” />

 <Txt />);

 } }

Lets update App Component

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

     render(){

               return(<button onClick={this.props.onClickFunction}>{this.state.counter}</button>); }

And in Button Component we will do something like this

State of component is only acessible by itself

class Button extends React.Component{

  handleClick = ()=>{

   this.props.onClickFunction(this.props.incrementcounter);

  };

render(){

   return(<button onClick={this.handleClick}>

     +{this.props.incrementcounter}

    </button>);

  }

}

const Txt = (props) => {

     return(<input type=”text” value={props.counter}/>);    

}

class App extends React.Component{

  state = { counter: 0 };

    handleClick = (val) => {

      this.setState((prevState)=>

      ({

        counter: prevState.counter + val

      }))

    };

  render(){

   return(<div>

     <Button incrementcounter={5} onClickFunction={this.handleClick} />        

        <Button incrementcounter={15} onClickFunction={this.handleClick} />     

        <Button incrementcounter={25} onClickFunction={this.handleClick} />     

        <Txt counter = {this.state.counter}/>

   </div>)

  }

}

ReactDOM.render(<App />, mountNode);

React has special property ref to refer to the particular element

Ref takes a function which executes once input element is mounted on the dom.

Using ref we read element value from the DOM
If we want to read the value of an element from React itself we will use 

————————————————————————————————————————–

https://app.pluralsight.com/player?course=aspdotnet-core-react-building-website&author=peter-kellner&name=b10d5415-ca95-48dc-9b11-5026a58623d7&clip=1&mode=live

React with Visual studio

Server side rendering is important 

Like we had aspnet pre rendering in .netcore + angular template

So the benefit of having server side rendering is you can have a prepared html as landing page to load landing page fast and without it you can’t have 404 page.

Lets learn Custom webpack configuration to integrate react with .net core app

*** skipped tutorials and jumped to 3.4 “bring in react and create the first component”

We need Babel transpiler to understand JSX syntax.

User crate-react-app

Npm install -g create-react-app

crate -react-app newreactapp

Navigate to /newreactapp and run “yarn install”

Once installed run “yarn start”

Adding SASS processing to create-react-app project.

SAAS( css pre processor)

Add some packages to your package.json file

State:

The data user see, 

The data we are fetching

The url shown to the user

Selected items inside page

Application errors 

All these things are state of the application and every javascript application has all this information.

So all we need here is to track this information so wo do it in react component.

To manage all this at one place we have redux

Redux holds up state within single location

Logic for fetching and managing state in redux lives outside of react.

We can use Redux with Vue JS and Angular too

Like many other libraries Redux is actually a state management library and we may not have it in future but concepts will remain same for every other library we might have.(like oop concepts remains same for php, c#, java etc)

When to use Redux?

We can consider children props before reaching out for redux https://daveceddia.com/context-api-vs-redux/

When react components don’t have parent child relationship and need to share same state

When its awkward to pass state down to too many react components.

Redux not useful in smaller apps it shines in bigger ones.

Store: State of whole application lives inside the store

1- create folder store 

2- create index.js //src/js/store/index.js

3- import create store and root reducer like this

  1. import { createStore } from “redux”;
  2. import rootReducer from “../reducers/index”;

4- pass the root reducer to create store function 

  1. const store = createStore(rootReducer);

5- now export created store

  1. export default store;

crateStore is a function for creating Redux store and it takes reducer (in our case rootReducer) as argument

For server side rendering you may pass initial state to create store method but normally we don’t.

Reducers?

1- Redux reducers produce the state

2- Initial state is useful for Server side rendering but it must return state from reducer

3- Reducer actually a javascript function takes two parameters 

1- current state

2- action

4- Reducer function must be pure (Pure function is one which returns exact same output for given input)

5- State is immutable in Redux, However in plain react you change state using setState method

Lets create a reducer function taking initial state as first parameter and action as second parameter. For now reducer will do nothing but returning current state.

Create a folder named reducers

Create file index.js inside src/js/reducers

  1. const initialState = {
  2.  articles: []
  3. };
  4.  
  5. const rootReducer = (state = initialState, action) => state;
  6.  
  7. export default rootReducer;

Our first reducer is so simple its doing nothing but returning initial state.

Reducer produces state of application but how it comes to know when to produce next state?

The only way to change the state is by sending signal to store, What is signal? Signal is an action, So “dispatching an action” is signal for store.

How do we change immutable state?

We don’t change we actually will return copy of current state + data.

Actions (we are passing as second param to reducer) are actually javascript objects.

  1. {
  2.  type: ‘ADD_ARTICLE’,
  3.  payload: { name: ‘React Redux Tutorial’, id: 1 }
  4. }

Every action has a type property describing how the state should change

Payload is here describing what to add/change to current state, a reducer will add that article to the current state later.

Best practice is to wrap action inside a function known as action creator

Create directory for actions /src/js/actions

Create file index.js //src/js/actions/index.js

  1. export const addArticle = article => ({ type: “ADD_ARTICLE”, payload: article });

As type is just a string telling how to change the state 

But the problem is typos to avoid any such errors we can use constants 

So let’s create constant file

Create directory for constants //src/js/constants

Create file action-types.js inside //src/js/constants

  1. export const ADD_ARTICLE = “ADD_ARTICLE”;

Now go back to //src/js/actions/index.js and update type with this constant

  1. import { ADD_ARTICLE } from “../constants/action-types”;
  2.  
  3. export const addArticle = article => ({ type: ADD_ARTICLE, payload: article });

————————-

Formik