Search code examples
javascriptreactjssonarqubesonarqube-scan

SonarQube code smell due to it ignoring `this` in two of three options


Here's an example of the issue I'm facing.

I suspect the reason I get this error on this block of code is because according to javascript:3AS3800...

Functions returning this are ignored.

Assuming this is the case, I'm having trouble coming up with a clean workaround.

    if (typeof (row) === 'string') {
      return (
        <Grid key={i}>
          <Divider className={classes.divider} />
            <Typography>
              { row }
            </Typography>
        </Grid>
      )
    }

    if (row.constructor === Array) {
      return row.map((item, index) => (
        <Grid key={index}>
          { this.getItem(item, formProps) }
        </Grid>
      ))
    }

    return (
      <Grid key={i}>
        { this.getItem(row, formProps) }
      </Grid>
    )
  }

Solution

  • For those that might stumble upon this, I misunderstood the error message.

    Sonarqube wants each return to be a value of the same type. In my example, the middle block returns a list of Grid components while the rest return solo Grid components. The solution was to return the solo Grid components as lists like so:

        if (typeof (row) === 'string') {
          return ([
            <Grid key={i}>
              <Divider className={classes.divider} />
                <Typography>
                  { row }
                </Typography>
            </Grid>,
          ])
        }
    
        if (row.constructor === Array) {
          return row.map((item, index) => (
            <Grid key={index}>
              { this.getItem(item, formProps) }
            </Grid>
          ))
        }
    
        return ([
          <Grid key={i}>
            { this.getItem(row, formProps) }
          </Grid>,
        ])
      }