How I decide to pass on a parameter within a component.
Why I chose to explicitly pass the tag parameter in LinkComponent.
When creating a component in Rails, especially when using a component-based architecture like ViewComponent or similar, I was faced with a question, how should I pass around and manage data, especially configuration data. Here i have 2 options.
1) Pass to BaseComponent
def call
content = prepare_content
render(RapidRailsUI::BaseComponent.new(tag: "a", **@options)) { content }
end
2) Pass to LinkComponent
class LinkComponent < Component
def initialize(
...
setup_options
end
def setup_options
@options[:tag] = "a"
...
end
end
Here's why I chose option 1, explicitly pass the tag parameter when calling BaseComponent from LinkComponent:
Clarity in Dependencies: By directly passing
tag: "a"
in therender
method, it becomes immediately clear what type of HTML elementBaseComponent
will render. This approach avoids confusion and errors that might arise from merging options where thetag
could be incorrectly overwritten or omitted.Ensuring Required Attributes: The
tag
attribute is essential forBaseComponent
to function correctly as it determines the HTML element type. Passing it explicitly ensures that the component always receives this necessary information, preventing runtime errors due to missing attributes.Separation of Concerns:
LinkComponent
should not be concerned with the internal workings ofBaseComponent
or how it processes its options. By passing thetag
directly,LinkComponent
remains focused on its specific logic, enhancing maintainability and keeping the components loosely coupled.
This method of passing parameters enhances code readability, reliability, and maintainability, making it easier to understand.
Happy coding 💻