how to use context api in react class component code example
Example 1: reactjs context
==App.js========================================
import React from 'react';
import PageContextProvider from './PageContextProvider';
import Header from './Header';
function App() {
return (
<div className="App">
<PageContextProvider>
<Header />
</PageContextProvider>
</div>
);
}
export default App;
==PageContextProvider.js=========================
import React, { useState, useEffect, createContext } from 'react';
export const PageContext = createContext();
const PageContextProvider = (props) => {
const [user, setUser] = useState({
'name': 'harry potter'
});
return (
<PageContext.Provider value={{
user: user,
}}>
{props.children}
</PageContext.Provider>
);
}
export default PageContextProvider;
==Header.js=====================================
import React, { useContext } from 'react';
import { PageContext } from './PageContextProvider';
const Header = () => {
const { user } = useContext(PageContext);
return (
<div className="header">
{user.name}
</div>
);
}
export default Header;
Example 2: react context api
DEFINITION::::::
Context provide a way to pass data through the component tree without
having to pass down manually at every level
HOW TO USE::::::
DECLARATION:::
const MyContext = React.createContext()
Creating a new Context for each unique piece of data that needs to be available
throughout your component data
const LocaleContext = React.createContext()
Properties of LocaleContext --------
LocaleContext.Provider
LocaleContext.Consumer
What is a Provider
Allows us to "declare the data that we want available throughout our
component tree"
What is a Consumer
Allows "any component in the tree that needs that data to be able to
subscibe to it"
How to use Provider
<MyContext.Provider value={data}>
<App />
</MyContext.Provider>