React JS Complete Tutorial

React JS introduction

React JS is a Java script library for building  user interfaces, this library developed by Meta(Facebook).

using react js you are able to break down complex interfaces in simple component, in react js every component is a separate function and has own properties that are called state. today most of the popular websites and mobile apps using react js to create more advanced systems.

Installation of react js

To install react js, make sure you have package manager NPM or YARN installed on your computer system.
Just run this command
npx create-react-app your_app_name

Creact first react component

We will use modern JS concept of META, we will create all components using function not class.
In React JS every component is a function, and every component render data using JSX syntax.
let Header=()=>{
return(
<div>
<header>Header of web page</header>
</div>
)
}

let Footer=()=>{
return(
<div>
<footer>Footer of web page</footer>
</div>
)
}

Exporting, Importing Component/Data in react js

let Register=()=>{
return(
<>
<h1>Register form</h1>
</>
)
}

export default Register;

importing component

import Register from .....path_of_file

Using JSX

JSX is a syntax extension for JS language, using JSX HTML tags can be write within JS file. 
When you are writing JSX in a component, keep remember some rules.
  1. Wrap all syntax in a single parent root, that can be any thing but when you does not need any kind of DOM element due to some kind of styling or other you can use empty tag <> </> it called React fragment.
  2. Close all tags properly.
    <h1></h1>

Java script in JSX using curly brackets.

Using single curly brackets {}, you can pass attribute value dynamically, you can write js expression and can call a function

using double curly brackets

Styling component or elements in a component, or passing object to an attribute, double curly bracket {{}} is used.
<h1 style={{backgroundColor:'yellow', color:'blue'}}>
Header of web page
</h1>
<Person details={{name:'Rama', age:20, country:'India'}} />

Styling react component

Styling component or elements in a component, or passing object to an attribute, double curly bracket {{}} is used.
<h1 style={{backgroundColor:'yellow', color:'blue'}}>
Header of web page
</h1>

Passing props to component

let Person=({name, age})=>{
return(
<>
Hello {name}, you are {age} year old
</>
)
}
<Person name="Rama" age="20" />

Conditional rendering

Rendering lists(map, filter function)

style attributes

Fragments

Responding to events

Hooks

  1.  useState()
  2.  useEffect()
  3.  useReducer()
  4.  useContext()
  5.  useCallback()
  6.  useMemo()
  7.  useRef()

useState

Return a value and a function to update it.

let [user, setUser]= useState('');

use this state

Your name is {user}

Update this state

<button type="button" onClick={()=>setUser('Rama')}>Update user</button>

useEffect

Logging, timers, any other mutations in a app is called side effects, and these side effects does not allowed directly in a function, these side effects can be used in useEffect() hooks.

A function passed to this useEffect function run after the every render.

Note: Effect run after every completed render, but we can use to run the function on only when certain values have changed.

Run on every render

useEffect( ()=>{
 let i = setInterval( ()=>{
 console.log(new Date().getHours()%12 );
}, 1000);
});

Run once.

useEffect( ()=>{
 let i = setInterval( ()=>{
 console.log(new Date().getHours()%12 );
}, 1000);
},[ ]);

useReducer

const TaskList=[
  {
    id:1,
    name:'Buy a mobile',
    completed: true
  },
  {
    id:2,
    name:'Buy vegetables',
    completed:false
  },
  {
    id:3,
    name:'Visit to a school',
    completed:true
  }
];
export default TaskList;

 

import {useReducer} from 'react';
import TaskList from './data/TaskList';
let App=()=>{

  let taskReducer=(tasks, action)=>{        
    switch(action.type){
      case 'ADD':        
        return tasks;
      case 'EDIT':
        return tasks;
      case 'DELETE':
        return tasks.filter( t => t.id !== action.id );   
      case 'CHANGE_STATUS':
        return tasks.map( t => {
          if( t.id === action.id){
            if( action.status === 'completed'){
              return {
                ...t,
                completed: true
              }
            }
            else if(action.status === 'not_completed'){
              return{
                ...t,
                completed: false
              }
            }
          }     
          return t;               
        });
      default :
      break;
    }
  }

  let editHandler=(id)=>{
    // alert(id);
    dispatch({type:'EDIT', id: id})
  }
  let deleteHandler=(id)=>{
    dispatch({type:'DELETE', id: id})
  }
  let changeStatus=(id, status)=>{
    if(status === 'completed'){
      dispatch({type:'CHANGE_STATUS', id: id, status: 'completed'})
    }
    else if(status === 'not_completed'){
      dispatch({type:'CHANGE_STATUS', id: id, status: 'not_completed'})
    }
  }

  let [tasks, dispatch] = useReducer(taskReducer, TaskList);
  
  return(
    <>
      <ul>
        {
        tasks.map(item=>{
          return(
            <li key={item.id}>
              {item.completed ? <del>{item.name}</del> : item.name }
              <button type="button" onClick={()=>editHandler(item.id)}>Edit</button>
              <button type="button" onClick={()=>deleteHandler(item.id)}>Delete</button>
              { item.completed ? <button type='button' onClick={()=> changeStatus(item.id, 'not_completed') }>Mark not completed</button> : 
              <button type='button' onClick={()=> changeStatus(item.id , 'completed')}>Mark completed</button> }
            </li>
          )            
          }
        )
        }
      </ul>
    </>
  )
}
export default App;

useCallback

This return memoized callback.

 You can pass a callback and array of dependencies of that callback and useCallback will return a memoized version of the callback and will only change when dependencies has changed.

This is useful when passing a callback to optimized child components.

useMemo

This return momoized value.

You can pass a function and array of dependencies for a function and useMemo will return a memoized value, and will only change when dependencies has changed.

React router

immer package

Formik package

© 2016 - 2022, All Rights are Reserved.