This repository has been archived by the owner on Jun 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Dra ut window.innerWidth til en provider for gjenbruk av state
- Loading branch information
Showing
3 changed files
with
40 additions
and
13 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import { createContext, ReactNode, useContext, useEffect, useState } from 'react'; | ||
|
||
interface WindowInnerWidthProps { | ||
innerWidth: number; | ||
} | ||
|
||
const WindowInnerWidthContext = createContext<WindowInnerWidthProps>({ innerWidth: window.innerWidth }); | ||
function WindowInnerWidthProvider(props: { children: ReactNode }) { | ||
const [innerWidth, setInnerWidth] = useState<number>(window.innerWidth); | ||
|
||
useEffect(() => { | ||
const updateInnerWidth = () => { | ||
setInnerWidth(window.innerWidth); | ||
}; | ||
|
||
window.addEventListener('resize', updateInnerWidth); | ||
|
||
return () => window.removeEventListener('resize', updateInnerWidth); | ||
}, []); | ||
|
||
return <WindowInnerWidthContext.Provider value={{ innerWidth }}>{props.children}</WindowInnerWidthContext.Provider>; | ||
} | ||
|
||
function useWindowInnerWidth() { | ||
const context = useContext(WindowInnerWidthContext); | ||
|
||
if (context === undefined) { | ||
throw new Error('useWindowInnerWidth må brukes under en WindowInnerWidthProvider'); | ||
} | ||
|
||
return context; | ||
} | ||
|
||
export { WindowInnerWidthProvider, useWindowInnerWidth }; |
This file contains 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
This file contains 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