I am using function component ,and now I want to pass itself to another objects.
import GlobalParam from './GlobalParam'
const TopPage = (props) =>{
const [load, setLoad] = useState(false);
useEffect(() =>{
GlobalParam.topPage = this;// however it does not work in function component.
})
}
in GlobalParam
export default class GlobalParam {
static topPage;
}
If I can pass conponent function itself to static class,
I can load the topPage from anywhere GlobalParam.topPage.setLoad(true);
What should I use in function component instead of this?
Take a look at useContext.
You can define a context with createContext (you can specify defaultValue but it's out of the scope of this example)
import { createContext } from "react";
const LoadContext = createContext();
export default LoadContext;
Then you can wrap your app with a Provider that will make available variables and functions to all its children
import TopPage from './TopPage';
import Debug from './DebugButton';
import { createContext, useState } from 'react';
import LoadContext from './LoadContext';
function App() {
const [load, setLoad] = useState(false)
return (
<LoadContext.Provider value={{load, setLoad}}>
<TopPage />
<Debug />
</LoadContext.Provider>
);
}
export default App;
and then you can access the context with useContext hook!
import {useContext} from 'react';
import LoadContext from './LoadContext';
const TopPage = (props) => {
const {load} = useContext(LoadContext)
return (
<div>
{load? <h1>loading</h1>: <h1>not loading</h1>}
</div>
);
};
export default TopPage;
and another component I made just for testing purpose
import { useContext } from "react"
import LoadContext from "./LoadContext"
const DebugButton = () => {
const {setLoad} = useContext(LoadContext)
return <button onClick={()=>{setLoad(v=>!v)}}>Debug</button>
}
export default DebugButton
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With