Setting up a nested slot #1647
Unanswered
boardfish
asked this question in
Show and tell
Replies: 2 comments 1 reply
-
@boardfish clever! Almost feels like a |
Beta Was this translation helpful? Give feedback.
1 reply
-
Updated syntax to leverage Ruby 2.7+ argument forwarding with # frozen_string_literal: true
class ParentComponent < ViewComponent::Base
renders_one :child, ChildComponent
def with_grandchild(...)
with_child { |child| child.with_grandchild(...) }
end
end |
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
-
Thanks to @neanias for prompting this.
You may have three layers of depth you'd like to travel through with components. Say you have a
ParentComponent
that renders aChildComponent
, which itself renders aGrandchildComponent
, and you'd like to access thegrandchild
from theParentComponent
.You can do so by defining a method
with_grandchild
on yourParentComponent
, like this:Now, instead of needing to traverse through all three layers...
You can instead...
with_grandchild
callswith_child
on theParentComponent
, which sets up thechild
slot to be ready to acceptwith_grandchild
. If you'd still like to configure thechild
slot, then you might need to use the first example. And if you're worried about folks not callingwith_grandchild
and thus not having achild
set at all, then I'd suggest using this pattern.EDIT: You can pass a block through too. I've updated the method signature to show that.
Beta Was this translation helpful? Give feedback.
All reactions