Pass data parent to child component and child to parent.
Provide using pass value. parent to child component.
Without manually pass data.
Run this code and see the output. using Provider in app.js file pass day Tuesday. and in child component ChildUseContext button onClick pass Day data to parent component.
App.js file code
import { createContext, useState } from 'react';
import ChildUseContext from './Pages/ChildUseContext';
export const globalDay = createContext();
function App() {
let [day, stDay] = useState('Tuesday');
let setDay = (day) => {
console.log('day------>', day);
stDay(day);
}
return (
<div className="App">
<globalDay.Provider value={{day:day, setDay}}>
<ChildUseContext />
</globalDay.Provider>
</div>
);
}
export default App;
Pages/ChildUseContext.js file code
import React, { useContext } from "react";
import { globalDay } from "../App";
function ChildUseContext() {
const {day, setDay} = useContext(globalDay);
return(
<>
<h3>ChildUseContext Example : Day {day}</h3>
<button onClick={() => { setDay('Monday'); }}>Click Day</button>
</>
);
}
export default ChildUseContext;
No comments:
Post a Comment