Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional rendering of component in Next js

I used to render a component depending on the screen width by writing something like this.

function App(props) {
    const [mobile, setMobile] = useState(() => window.innerWidth < 576 ? true : false)
    return (
        <div>
            {
                mobile ? <ComponentA /> : <ComponentB />
            }
        </div >
    );
}

But now that I'm using Next.js this gives me several errors due to the window.innerWidth reference. How could I do this? Thanks in advance.

like image 907
Diego Avatar asked Oct 24 '25 09:10

Diego


1 Answers

You are getting a reference error because you cannot access the window object in useState. Instead, you have to set the initial value in useState to undefined or null and use useEffect where window can be referenced to call setMobile(window.innerWidth < 576 ? true : false). finally, in your render method, you can check whether mobile state is set using setMobile (i.e., not undefined or null) and use the defined mobile state value (either true or false) to conditionally render your ComponentA or ComponentB. Also, you need to add window.addEventListener('resize', handleResize) when your App component is mounted and remove it when it is unmounted, which you also do in useEffect since that is where you get reference to window. Otherwise, resizing the browser will not trigger an update to mobile state. Here is a working example:


import React, { useState, useEffect } from 'react'

function App() {
  const [mobile, setMobile] = useState(undefined)

  useEffect(() => {
    const updateMobile = () => {
      setMobile(window.innerWidth < 576 ? true : false)
    }

    updateMobile()
    window.addEventListener('resize', updateMobile)
    return () => {
      window.removeEventListener('resize', updateMobile)
    }
  }, [])

  return typeof mobile !== 'undefined' ? (
    mobile ? (
      <ComponentA />
    ) : (
      <ComponentB />
    )
  ) : null
}
like image 65
kimbaudi Avatar answered Oct 25 '25 22:10

kimbaudi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!