Action on window resize in React
It is also possible using React Hooks
import React from 'react';
function useWindowDimensions() {
const [width, setWidth] = React.useState(window.innerWidth);
const [height, setHeight] = React.useState(window.innerHeight);
const updateWidthAndHeight = () => {
setWidth(window.innerWidth);
setHeight(window.innerHeight);
};
React.useEffect(() => {
window.addEventListener("resize", updateWidthAndHeight);
return () => window.removeEventListener("resize", updateWidthAndHeight);
});
return {
width,
height,
}
}
const App = () => {
const { width, height } = useWindowDimensions()
return (
<div>
<div className="App">
<h2>width: {width}</h2>
<h2>height: {height}</h2>
<p>Resize the window.</p>
</div>
</div>
);
};
export default App;
When you change the window size - the size of the h1
element will not necessary change, so it isn't guaranteed that your code will run.
What you can do is use the DOM event of resize
on the window
element to call your function:
class Welcome extends React.Component {
constructor() {
super();
this.state = {
WindowSize : window.innerWidth
}
this.handleResize = this.handleResize.bind(this);
}
componentDidMount() {
window.addEventListener("resize", this.handleResize);
}
componentWillUnmount() {
window.addEventListener("resize", null);
}
handleResize(WindowSize, event) {
this.setState({WindowSize: window.innerWidth})
}
render() {
return <h1 hidden={(this.state.WindowSize < 1024) ? "hidden" : ''}>Hello</h1>;
}
}
ReactDOM.render(
<Welcome/>,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root">
</div>