Next.js Discord

Discord Forum

I want to transfer a boolean value from a component running on the client side to the server side

Answered
Mini Satin posted this in #help-forum
Open in Discord
Mini SatinOP
Hello. I want to show the mobile version if the user is accessing the site from mobile, otherwise I want to show the normal version. I have a client component to understand that it is a mobile version:

ver-control.tsx --->

'use client' import { useEffect, useState } from 'react' export const VersionControl = () => { const [isMobile, setIsMobile] = useState(false) useEffect(() => { const mobileControl = /iPhone|iPad|iPod|Android|webOS|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); mobileControl ? setIsMobile(true) : setIsMobile(false) },[]) return isMobile }

Then I meet this component in a server component as follows:

page.tsx --->
import { VersionControl } from "@/components/ver-cont"; const page = () => { const isMobile = VersionControl() return ( <div> {isMobile ? <MobileVersion /> : <NormalVersion /> } </div> ) } export default page

But I get this error:
Attempted to call VersionControl() from the server but VersionControl is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.

How should I proceed?
Answered by Nelson
@Mini Satin
import { headers } from "next/headers";

export default function Home() {
  const headersList = headers();
  const userAgent = headersList.get("user-agent");
  const isMobile =
    /iPhone|iPad|iPod|Android|webOS|BlackBerry|IEMobile|Opera Mini/i.test(
      userAgent as string
    );

  return <div>{isMobile ? <MobileVersion /> : <NormalVersion />}</div>;
}
View full answer

9 Replies

@Mini Satin You're using hooks in the page. So, you need to add 'use client' to the top of page.tsx
@Nelson <@305787918461698054> You're using hooks in the page. So, you need to add `'use client'` to the top of `page.tsx`
Mini SatinOP
@Nelson I threw an empty 'page.tsx' here as an example. Normally I have a page with server components.
@Mini Satin But you can't call hooks on server side.
Mini SatinOP
@Nelson Is there any way to overcome this without using hooks?
@Mini Satin
import { headers } from "next/headers";

export default function Home() {
  const headersList = headers();
  const userAgent = headersList.get("user-agent");
  const isMobile =
    /iPhone|iPad|iPod|Android|webOS|BlackBerry|IEMobile|Opera Mini/i.test(
      userAgent as string
    );

  return <div>{isMobile ? <MobileVersion /> : <NormalVersion />}</div>;
}
Answer
Mini SatinOP
:aww:
I don't know how to thank you. I've been working on this for four hours. You made my day. I'm so grateful to you.