Reputation: 1
is there a way to import a function from component in ReactJS Hooks? Like, I have this component and function:
export default const Test(){
const [state, setState] = useState(0);
function TestFnc(){
setState(20)
}
return(
<p>{state}</p>
)
}
And I wonder how can I use that function TestFnc
inside of other component? like this:
export default const Component(){
return(
<p onClick={()=> TestFnc()}>click me</p>
)
}
I know I could use class reactjs and export it to window DOM and use like this: window.Test.TestFnc()
but with hooks is possible?
I tried custom Hooks but custom hooks didn't update the state I've forgotten to mention, these components aren't related, they aren't parent and children.
Upvotes: 0
Views: 62
Reputation: 1
I've exported my function to DOM like this:
useEffect(() => {
window.resetSearch = resetSearch;
}, []);
Upvotes: 0
Reputation: 192
You can either pass that function via props to the children of that component like this:
const ChildComponent = (props) => {
return <button onclick={() => props.fn()} />
}
const ParentComponent = () => {
const myFn = () => {};
return <ChildComponent fn={myFn} />
}
or use the React's Context API, with Context the idea stays the same, but is a little more flexible as you can avoid prop-drilling.
Upvotes: 1