Get the current browser screen width in React.js?

Answered
itsbambi asked this question 1 year, 5 months ago
itsbambi on Dec 14, 2021 · Edited

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?

2 suggested answers
looper003 on Dec 22, 2021
window.innerWidth

That will return the width of the browser window. This includes the vertical scroll bar.

0 replies
suparman21 on Dec 22, 2021

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:

  • When the component is mounted, we set the this.state.width value to the current browser width. And create a event listener that is triggered every time the browser is resized.
  • When the event listener is triggered, the updateWindowWidth() function is called, which sets the new browser width in the state.
  • When the component is about to unmount, the event listener is removed.
0 replies
Answered