Last active
September 21, 2019 19:42
-
-
Save drublic/cbb99a906f8fd349298ce32b2c3b6bc8 to your computer and use it in GitHub Desktop.
Conceptual Hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Higher-Order Component | |
// contains the state and life-cycle behavior of the component | |
import React, { FunctionComponent, useState, useCallback } from "react"; | |
import Button from "./Button"; | |
import useHasLoader from "./hooks/useHasLoader"; | |
interface Props { | |
isLoading: boolean; | |
} | |
const withButton = ( | |
Component: FunctionComponent<any> | |
): FunctionComponent<Props> => ({ isLoading, ...props }) => { | |
const [hasFocus, setHasFocus] = useState<boolean>(false); | |
const [hasLoader, setHasLoader] = useState<boolean>(false); | |
const handleFocus = useCallback(() => { | |
setHasFocus(true); | |
}, []); | |
const handleBlur = useCallback(() => { | |
setHasFocus(false); | |
}, []); | |
useHasLoader({ | |
isLoading, | |
hasFocus, | |
setHasLoader | |
}); | |
return ( | |
<Component | |
hasLoader={hasLoader} | |
onFocus={handleFocus} | |
onBlur={handleBlur} | |
{...props} | |
/> | |
); | |
}; | |
export default withButton(Button); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Custom Hook for logic | |
import { useEffect } from "react"; | |
const useHasLoader = ({ isLoading, hasFocus, setHasLoader }) => { | |
useEffect(() => { | |
if (isLoading && !hasFocus) { | |
return setHasLoader(true); | |
} | |
return setHasLoader(false); | |
}, [isLoading, hasFocus, setHasLoader]); | |
}; | |
export default useHasLoader; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment