import React, {useReducer, useState, createContext, useContext} from "react";
//===============Part 1=================
const initStateValue={
Name:"Sabir",
Contact:"033333444",
Roll:"99494"
};
//==============Reducer===Action==List
function SetStudentReducer(state,action) {
return {
Name:action.name,
Contact:action.contact,
Roll:action.roll
}
}
//===============Use Reducer=========
export function TestReducerComponent() {
//=====================
const [name,setName]=useState('');
const [contact,setContact]=useState('');
const [roll,setRoll]=useState('');
//=========Use Reducer============
const [state,dispatch]=useReducer(SetStudentReducer,initStateValue);
function Update() {
dispatch({
name:name,
contact:contact,
roll
});
}
return <>
<input onChange={(e)=>setName(e.target.value)} placeholder={"Name"}/><br/>
<input onChange={(e)=>setContact(e.target.value)} placeholder={"Contact"}/><br/>
<input onChange={(e)=>setRoll(e.target.value)} placeholder={"Roll"}/><br/>
<button onClick={Update}>Update</button>
<br/>
<hr/>
<br/>
<h1>Name {state.Name}</h1>
<h1>Contact {state.Contact}</h1>
<h1>Roll {state.Roll}</h1>
</>
}
//===============Part 2=================
//=======Context Api=============
const testContextApi=createContext();
export function DivContext({children,color}) {
//=====================
const [pass,setPass]=useState('');
//Reducer
// const [state,dispatch]=useReducer(SetStudentReducer,initStateValue);
//=====================
return <testContextApi.Provider value={{pass,setPass}}>
<div style={{backgroundColor:color}}>
{children}
</div>
</testContextApi.Provider>
}
//=============Use===============
//Parent Component
export function UseContextComponent() {
return <>
<DivContext color={"Blue"}>
<TestA/>
<Display/>
</DivContext>
</>
}
//Children Component value Update
function TestA() {
const {setPass}=useContext(testContextApi)
return <>
<h1>Update Value</h1>
<input onChange={(e)=>setPass(e.target.value)} placeholder={"password"} /><br/>
</>
}
//Children Component value Show
function Display() {
const {pass}=useContext(testContextApi)
return <>
<h1>Display</h1>
<h5>{pass}</h5>
</>
}
Comments
Post a Comment