Answer the question
In order to leave comments, you need to log in
What is the equivalent of Vue.mixin in React?
When writing projects in Vue, I quite often resorted to using a plugin (which was a global mixin) to get screen sizes. That is, I could use this.windowWidth and this.windowHeight anywhere in the application and it was as convenient as possible.
Now there is a need to do something similar in React. I originally wrote a hook that dynamically returns the window dimensions:
import {useState, useEffect} from 'react'
export const useWindowSize = () => {
const [size, setSize] = useState({
width: window.innerWidth,
height: window.innerHeight
})
const updateWindowSize = () => {
setSize({
width: window.innerWidth,
height: window.innerHeight
})
}
useEffect(() => {
window.addEventListener('resize', updateWindowSize)
return window.removeEventListener(updateWindowSize)
}, [])
return size
}
import WindowSize from './WindowSize';
const {width, height} = useContext(WindowSize)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question