Context API in React Tut 11
Context API in React
The Context API is a component structure provided by the React framework, which enables us to share specific forms of data across all levels of the application.
A.jsx ==> B.jsx ==> C.jsx
if we want to send the data from A to C , then we have to pass it through B via concept of props
, but if we want to send the data directly from A to C .
So for that we need to use concept of context API .
Practical of this concept as follow :
File hierachy is as Follow :
ContextAPI.jsx ==> ComA.jsx ==> ComB.jsx ==>ComC.jsx
file : ContextAPI.jsx
import React, { createContext } from 'react';
import ComA from './ComA';
var FilmName = createContext();
let ContextAPI = () => {
return (
<>
<FilmName.Provider value={'GolMaal film'}>
<ComA />
</FilmName.Provider>
</>
)
}
export default ContextAPI;
export {FilmName};
file : ComA.jsx
import React from 'react';
import ComB from './ComB';
let ComA = ()=>{
return(
<>
<ComB/>
</>
)
}
export default ComA ;
file : ComB.jsx
import React from 'react';
import ComC from './ComC';
let ComB = ()=>{
return(
<>
<ComC/>
</>
)
}
export default ComB ;
file : ComC.jsx
import React from 'react';
import { FilmName } from './ContextAPI';
let ComC = () => {
return (
<>
<FilmName.Consumer>
{(film) => { // it is callback function which contain context value
return (
<>
<h1>GolMaAL HAi Bhai SAb GoLmAaL Hai</h1>
<h2>{film}</h2>
</>
)
}}
</FilmName.Consumer>
</>
)
}
export default ComC;
file : ContextAPI.jsx
import React, { createContext } from 'react';
import ComA from './ComA';
var FilmName = createContext();
var Earned = createContext();
let ContextAPI = () => {
return (
<>
<FilmName.Provider value={'GolMaal film'}>
<Earned.Provider value={'25 crore'}>
<ComA />
</Earned.Provider>
</FilmName.Provider>
</>
)
}
export default ContextAPI;
export { FilmName , Earned };
file : ComA.jsx
import React from 'react';
import ComB from './ComB';
let ComA = ()=>{
return(
<>
<ComB/>
</>
)
}
export default ComA ;
file : ComB.jsx
import React from 'react';
import ComC from './ComC';
let ComB = ()=>{
return(
<>
<ComC/>
</>
)
}
export default ComB ;
file : ComC.jsx
import React from 'react';
import { FilmName, Earned } from './ContextAPI';
let ComC = () => {
return (
<>
<FilmName.Consumer>
{
(film) => { // it is callback function which contain context value
return (
<>
<Earned.Consumer>
{
(Earn) => {
return (
<>
<h1>GolMaAL HAi Bhai SAb GoLmAaL Hai</h1>
<h2>{film}</h2>
<h3>Earning of Film {Earn}</h3>
</>
)
}
}
</Earned.Consumer>
</>
)
}
}
</FilmName.Consumer>
</>
)
}
export default ComC;
Comments
Post a Comment