How to pass props or states from parent(child-component) to the child(server-component)?

158 views Asked by At

I have a server api call that requires user's ip address. for tracking the user, I am using a third party api.

Now, the problem that i'm mainly facing is, the client side codes cannot be loaded on the "view page source" tab. To fix this issue, i am planning to make another api call just to load the data on the server side. for this, i need to pass the ip address from client to server. I've found a solution for doing this from the nextjs's documentation on the url: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-server-with-fetch

but i'm not sure about how to pass props to the children.

Let's say the "ServerComponent" is wrapped by a client-component named "ClientComponent"

<ClientComponent>
      <ServerComponent />
    </ClientComponent>

Also assume that this is my client component and the server-component is passing as it's(the client component's) {children}

'use client'

import { useState } from 'react'
 
export default function ClientComponent({
  children,
}: {
  children: React.ReactNode
}) {
  const [count, setCount] = useState(0)

  return (
    <>
      <button onClick={() => setCount(count + 1)}>{count}</button>
      {children}
    </>
  )
}

Now, I need to pass a prop or state ip:{userIp} from the ClientComponent to the ServerComponent.

I've found a nextjs 13 approach to use server-component inside a client component. doc: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-server-with-fetch

But I dont know how to pass props to this server-component

1

There are 1 answers

1
Akeel Ahmed Qureshi On

You can try this way for passing the props from parent to child component :

import { useState } from 'react';
import ServerComponent from './ServerComponent'; // Import the ServerComponent

export default function ClientComponent() {
  const [count, setCount] = useState(0);
  const userIp = '...'; // Replace this with the user's IP address

  return (
    <>
      <button onClick={() => setCount(count + 1)}>{count}</button>
      <ServerComponent userIp={userIp} /> // pass props and states here 
    </>
  );
}