#StackBounty: #reactjs #data-structures #refactoring #javascript-objects #solid-principles How to refactor a react component that is ha…

Bounty: 50

I’d like to apply SOLID principles with a react component that’s handling too many ‘use cases’. As an example let’s say I have a component that’s main responsibility is to render a table like so:

return (
   <Table dataSource="" name={tableName} />

This is a very simplistic representation of that table. But the main point of complexity is the prop dataSource. Inside this <Table> component, I actually have a lot of logic/if-else condition that’s catering for the dataSource flag littered within the component because the dataSource can take in many different shapes / object structure. Some are very similar that they can be abstracted, while some are quite specific (and may even just differ by one key).

For example:

const tableName = `${
    dataSource === 'dataSourceA'
        ? dataSourceName
        : dataSourceName.name

This is just one example. Imagine some dataSource has its name property nested 3 levels deep. Then other dataSource will even have different names for the keys (although the resulting data that I need to render are actually the same). Not only that, depending on the dataSource, I may need to call a different endpoints to execute some functionalities (again, the function is doing the same purpose, just the endpoint can be different). Hence within the same component I’ll have a function like:

const exportTable = () => {
    if(dataSource === 'dataSourceA') {
        // use endpoint A
    } else if (dataSource=== 'dataSourceB') {
        // use endpoint B
    } else {
         // use endpoint C

What is the best way to refactor this kind of component and make it easier to maintain? Later on, we can have 10 types of dataSources and I can’t be doing if-else conditions within the component to cater for their differences.

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.