[app router] Render different component based on user agent #70701
Unanswered
dimitridumont
asked this question in
Help
Replies: 1 comment
-
I tried the same thing and i saw the script for Desktop being downloaded in the browser too. It's no use if it's still being downloaded not sure how to tackle. I create a re-usable hook "use server";
import React, {ReactNode, ComponentType} from "react";
import {parseUserAgent} from "@repo/helpers";
import dynamic from "next/dynamic";
import {headers} from "next/headers";
interface Props {
CommonWrapper?: ComponentType<{children: ReactNode}>;
MobileComponent: () => Promise<{default: React.ComponentType<any>}>;
DesktopComponent: () => Promise<{default: React.ComponentType<any>}>;
}
const withResponsiveLayout = async ({
CommonWrapper,
MobileComponent,
DesktopComponent,
}: Props) => {
const header = new Headers(headers());
const parsedUserAgent = parseUserAgent(header);
let isMobile = parsedUserAgent?.device.is("mobile");
const Wrapper = CommonWrapper ?? React.Fragment;
const Component = isMobile
? dynamic(MobileComponent)
: dynamic(DesktopComponent);
return (
<Wrapper>
<Component />
</Wrapper>
);
};
export default withResponsiveLayout;
// example
async function Page() {
const data = await getSomeData();
return await withResponsiveLayout({
CommonWrapper: ({children}: PropsWithChildren) => (
<MandatoryAuthWrapper>
<CommonProvier initialData={data}>{children}</CommonProvier>
</MandatoryAuthWrapper>
),
DesktopComponent: () => import("./Main"),
MobileComponent: () => import("./MobMain"),
});
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Summary
I am developing an e-commerce site with Next.js, in version 14.2.5 and the app router.
We want to have different versions of cache, more precisely a mobile version and a desktop version. The same goes for the rendering.
Our interface changes radically between the mobile version and the desktop version on some pages, which is why we decided to use the user agent to determine the version used by the user rather than media queries (to avoid shifting).
To do this, in our middleware, we modify a custom header in this way:
Then, in our components, we use this custom header to render one component or another. Example:
Is this a good way to manage the rendering and cache of a mobile version and a desktop version of the same site?
Additional information
No response
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions