How to pass props to server component from client component.
Answered
Mudi posted this in #help-forum
MudiOP
Hi Guys:
This is my page.tsx
This is my ServerComp.tsx
and finally my ClientComp.tsx
My doubt is how to send data from clinet comp to server comp, My brain is not working plz help me
This is my page.tsx
import ClientComp from "./ClientComp";
import ServerComp from "./ServerComp";
export default function Home() {
return (
<>
<ClientComp>
<ServerComp />
</ClientComp>
</>
);
}This is my ServerComp.tsx
import "server-only"
export default function ServerComp({ bval }: { bval?: number }) {
return (
<div>
<p>
this is Server COmponnent (userclicked: {bval})
</p>
</div>
)
}and finally my ClientComp.tsx
import { ReactNode } from "react"
export default function ClientComp({ children }: { children: ReactNode }) {
const handleCLick = (event: React.MouseEvent<HTMLButtonElement>) => {
alert(event.currentTarget.value)
}
return (
<div>
{children} (here i would like to send the bval argument which should be equal to the button clicked by the user)
<button value={1} onClick={handleCLick}>Button 1</button>
<button value={2} onClick={handleCLick}>Button 2</button>
<button value={3} onClick={handleCLick}>Button 3</button>
</div>
)
}My doubt is how to send data from clinet comp to server comp, My brain is not working plz help me
Answered by American Crow
You can't directly pass data.
You can
1) Restructure so your code moves from server components to the client
2) use a server action in your
3) fetch a route handler in your
4) set searchParams in url
You can
1) Restructure so your code moves from server components to the client
2) use a server action in your
handleClick3) fetch a route handler in your
handleClick4) set searchParams in url
?bval=2 in your handleClick. The searchParams can be directly read from your ServerComp via ServerComp({searchParams})2 Replies
American Crow
You can't directly pass data.
You can
1) Restructure so your code moves from server components to the client
2) use a server action in your
3) fetch a route handler in your
4) set searchParams in url
You can
1) Restructure so your code moves from server components to the client
2) use a server action in your
handleClick3) fetch a route handler in your
handleClick4) set searchParams in url
?bval=2 in your handleClick. The searchParams can be directly read from your ServerComp via ServerComp({searchParams})Answer
MudiOP
Thank you for the explanation