In React it's common to need to use a component but alter its layout or behavior to some degree.
This can be done in many ways. Each way has its own benefits and limitations, but I won't go into detail here.
- Props
<ListItem text="foo" textSize="md"/>- Composition
<ListItem>
<ListItemText size="md">foo</ListItemText>
</ListItem>This gist demonstrates another approach of solving this problem: createTemplateComponent. This function creates a new component given two parameters:
renderElementsReturns a record of elements that will be passed as props to the template component.defaultTemplateA react component that renders the elements provided byrenderElements. The component returned bycreateTemplateComponentwill use this component by default. This can be overridden by passing in a new template component aschildren.
The benefit of this approach is that it adds a layer of abstraction where the programmer can define important elements that should be able to be hand picked and reused from inside the component. A great use case is forms, where a templated form component could define all its controls and fields as elements, provide a default generic template while at the same time allow easy customization of the form layout via the template override.
See examples below.
i get the general idea, this would probably shorten my spaghetti code owo