Answered
In my React.js component, I'd like to conditionally render some elements depending on the screen width.
How do I get the current width of the user's screen? Is there a pure JavaScript solution?
window.innerWidth
That will return the width of the browser window. This includes the vertical scroll bar.
You can use the innerWidth
method:
window.innerWidth
Here's an example of how you could store the browser width in your browser and update it whenever a user changes its width:
export default class extends Component {
constructor(props) {
super(props)
this.state = {
width: 0
}
this.updateWindowWidth = this.updateWindowWidth.bind(this)
}
componentDidMount() {
this.setState({width: window.innerWidth})
window.addEventListener("resize", this.updateWindowWidth)
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateWindowWidth)
}
updateWindowWidth() {
this.setState({width: window.innerWidth})
}
render () {
return (
// your component elements
)
}
}
Code breakdown:
this.state.width
value to the current browser width. And create a event listener that is triggered every time the browser is resized.updateWindowWidth()
function is called, which sets the new browser width in the state.