I'm in need of getting the width of the browser when i resize the browser in real time. So far i've found a solution which gives the width but it's not in real time. The value is updated only after i refresh the web page. How can i get the value as i resize the browser.
My approach
render() {
var windowWidth = window.innerWidth;
return (
<div className="body_clr">
{windowWidth}
</div>
)
}
This solution works if i refresh the page. But i want to get the width as i resize because i have to execute a function at a specific screen size.
I'm in need of getting the width of the browser when i resize the browser in real time. So far i've found a solution which gives the width but it's not in real time. The value is updated only after i refresh the web page. How can i get the value as i resize the browser.
My approach
render() {
var windowWidth = window.innerWidth;
return (
<div className="body_clr">
{windowWidth}
</div>
)
}
This solution works if i refresh the page. But i want to get the width as i resize because i have to execute a function at a specific screen size.
Share Improve this question asked Aug 8, 2018 at 10:24 CraZyDroiDCraZyDroiD 7,10533 gold badges106 silver badges195 bronze badges 1- 1 stackoverflow./questions/19014250/… – brk Commented Aug 8, 2018 at 10:27
2 Answers
Reset to default 9Here's a way to do this:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
constructor() {
super();
this.state = {
height: 0,
width: 0
};
window.addEventListener("resize", this.update);
}
ponentDidMount() {
this.update();
}
update = () => {
this.setState({
height: window.innerHeight,
width: window.innerWidth
});
};
render() {
return (
<React.Fragment>
<p>height: {this.state.height}</p>
<p>width: {this.state.width}</p>
</React.Fragment>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Working CodeSandbox here.
You can use event listeners:
window.addEventListener("resize", function() {
return window.innerWidth;
});