context Provider react hooks code example
Example 1: useRef
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
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;
Example 3: usecontext hook
import React, { useContext } from "react";
import ColorContext from "./colorcontex.ts";
const MyComponent = () => {
const colors = useContext(ColorContext);
return <div style={{ backgroundColor: colors.blue }}>...</div>;
};import React, { useContext } from "react";
const MyComponent = () => {
const colors = useContext(ColorContext);
return <div style={{ backgroundColor: colors.blue }}>...</div>;
};