Reputation: 1
I've noticed some people writing a "renderSomething" method that returns some jsx. This renderSomething method is called within the actual render() of a react component.
Something like this simple example:
renderTab(title, isVisible) {
return (
<div>
... some html/jsx that uses title and isVisible
</div>
);
}
render() {
return (
<div>
{this.renderTab('Tab 1', true)}
{this.renderTab('Tab 2', true)}
{this.renderTab('Tab 3', false)}
</div>
);
}
Normally I would extract that renderSomething into it's own component:
render() {
return (
<div>
<Tab title='Tab 1' isVisible=true />
<Tab title='Tab 2' isVisible=true />
<Tab title='Tab 3' isVisible=false />
</div>
);
}
I think extracting it into it's own component makes it easier to test and goes well with the react's approach to components but I keep seeing this "renderSomething" pattern from multiple people. I am curious if there is a preferred best practices approach. Are either OK? Which one is considered best practice?
Upvotes: 0
Views: 152
Reputation: 927
My perspective; having worked on ReactJS applications at an enterprise level is this.
If you will render this content again somewhere else -> Component
If it takes more than 7 opening HTML/JSX tags to accomplish this -> Component
Realistically speaking all this code ends up being repeated over and over in your bundle anyway; but for the sake of maintainability Components are usually the best way to go.
As another matter of preference; when it comes to debugging I like to be able to note the component name that is giving me problems and head straight to a file with that name to investigate...rather than trying to find the relevant code in a file with a totally obscure relationship
e.g. "ListManager has an error" -> Go to list manager as opposed to the list manager in "Contacts" having the error where I then have to dig through the source of Contacts to find the list code.
In the case of your tabs IF I were to write a "renderSomething" version it wouldn't be with three calls to renderTab. I'd loop the tabs array to make the call with each tab item. Personal preference is what it all boils down too.
Upvotes: 1