Next.js Discord

Discord Forum

Pass props from Server Component to Client Component using App router

Answered
Acorn-plum gall posted this in #help-forum
Open in Discord
Acorn-plum gallOP
I have this code on page.js (Server Component):
           <Box
              sx={{
                display: "flex",
                flexWrap: "wrap",
                gap: 1,
                marginBottom: 1,
                justifyContent: "center",
              }}
            >
              {tool.tags.map((tag) => (
                <HiddenLink tag={tag}/>
              ))}
            </Box>

And this Client Component "HiddenLink":
"use client";

import { useRouter } from "next/navigation";
import Chip from "@mui/material/Chip";
import TagIcon from "@mui/icons-material/Tag";

export default function HiddenLink(tag) {
  const tag_data = JSON.stringify(tag)
  const tag_object = JSON.parse(tag_data)
  const router = useRouter();

  const handleClick = (() => {
    router.push(`${tag_object.tag.slug}`);
  });

  return (
    <Chip
      icon={<TagIcon />}
      label={tag_object.tag.name}
      clickable
      onClick={handleClick}
    />
  );
}

It works as I need, but I doubt that it's an efficient way because of these two lines in Client Component:
  const tag_data = JSON.stringify(tag)
  const tag_object = JSON.parse(tag_data)

It seems weird to me.
Do you have any ideas how to improve this code?
Answered by riský
why can't you just get the props like normal? as it is already doing the conversion to string https://nextjs.org/docs/app/building-your-application/configuring/typescript#passing-data-between-server--client-components
View full answer

2 Replies

why can't you just get the props like normal? as it is already doing the conversion to string https://nextjs.org/docs/app/building-your-application/configuring/typescript#passing-data-between-server--client-components
Answer
Acorn-plum gallOP
Yes, indeed, it works, I didn't use destructuring assignment in an argument { tag }. Thanks to you, now my code looks much more concise
export default function ChipHiddenLink({tag}) {
  const router = useRouter();

  const handleClick = (() => {
    router.push(`${tag.slug}`);
  });

  return (
    <Chip
      icon={<TagIcon />}
      label={tag.name}
      clickable
      onClick={handleClick}
    />
  );
}

Your link is in TypeScript chapter, but I don't use TypeScript, so didn't see the information. And the next text about serialization confused me https://nextjs.org/docs/getting-started/react-essentials#passing-props-from-server-to-client-components-serialization
"Props passed from the Server to Client Components need to be serializable. This means that values such as functions, Dates, etc, cannot be passed directly to Client Components."
Now everythink is ok. Thank you!