context.js code example

Example 1: context javascript

console.log(this);
// Window {0: Window, window: Window, self: Window, document: document, name: "", location: Location, …}

class MyClass {
	constructor(x, y){
    	this.x = x;
      	this.y = y;
      	this.sum = x + y;
    }
	printThis(){
    	console.log(this);
    }
}

myClass = new MyClass(3, 4);
myClass.printThis();
// MyClass {x: 3, y: 4, sum: 7}

Example 2: 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;