I have a code in my NextJs app to detect the userAgent. Which is totally okay for the NextJs pages. But, when I need to call this responsive isMobile
prop to the components (e.g: Footer, Header, Navigation) then what should I do?
// index.js
IndexPage.getInitialProps = ({ req }) => {
let userAgent;
if (req) { // if you are on the server and you get a 'req' property from your context
userAgent = req.headers['user-agent'] // get the user-agent from the headers
} else {
userAgent = navigator.userAgent // if you are on the client you can access the navigator from the window object
}
let isMobile = Boolean(userAgent.match(
/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop/i
))
return { isMobile }
}
Now I can access the
isMobile
prop that will return either true or false
const IndexPage = ({ isMobile }) => {
return (
<div>
{isMobile ? (<h1>I am on mobile!</h1>) : (<h1>I am on desktop! </h1>)}
</div>
)
}
It is not happening in your components because they will be rendered client-side but whenever you hit a page (SSR) the request header will be updated with the current agent.
So if you are about to use isMobile
props for responsive design it's actually not helpful because on the browser the media queries are just understandable otherwise you can detect your agent every time your page hits (SSR) and store it somewhere like redux store and then use in you child components.
but if for example, you click on a link in the footer and render another component the Agent is not going to be updated.