Reference to parent server component in client component
Answered
Masai Lion posted this in #help-forum
Masai LionOP
Hello!
I'm working on some form components for our Next apps, and I'm trying to anticipate the day we start using server components. I have this input component that could totally be used as a server component except for one feature: a "clear" button that appears on the side when the field is not empty. Although I can manage the visibility of this button entirely in CSS, what happens when I click on it needs a client only piece of code.
I wondered if I could extract just this button as a client component, but for it to work I would need to give it a reference to the input field rendered in the main component, but I don't know how I could do that while keeping the main component server side (which means I cannot use
Is there a way to do that?
I'm working on some form components for our Next apps, and I'm trying to anticipate the day we start using server components. I have this input component that could totally be used as a server component except for one feature: a "clear" button that appears on the side when the field is not empty. Although I can manage the visibility of this button entirely in CSS, what happens when I click on it needs a client only piece of code.
I wondered if I could extract just this button as a client component, but for it to work I would need to give it a reference to the input field rendered in the main component, but I don't know how I could do that while keeping the main component server side (which means I cannot use
useRef in it. Is there a way to do that?
Answered by B33fb0n3
well, yes. The server itself doesn't know any states. So the server can't say "now I clear it" and "now it change it". The server doesn't have any interactivity. You can set an id on the element (serverside), so the textfield stays on the serverside and then get the element by it's id on the clientside
7 Replies
you can create a component, that is a client component that contains only the textfield and the clear button. Then the clear button can reference to the textfield and clear it. A client component inside a server component is allowed and possible @Masai Lion
Masai LionOP
Yes, I know that, but I would have liked the textfield itself to remain a server component, but maybe that's not possible 🤷ðŸ¼â€â™‚ï¸
well, yes. The server itself doesn't know any states. So the server can't say "now I clear it" and "now it change it". The server doesn't have any interactivity. You can set an id on the element (serverside), so the textfield stays on the serverside and then get the element by it's id on the clientside
Answer
Masai LionOP
Ah, and I would use native browser API in the client side component to clear the field... 🤔
yes
Masai LionOP
Thanks!
cool, please mark solution