Eslint-plugin-react: `react/require-render-return` doesn't account for switch statement

Created on 12 Apr 2016  路  5Comments  路  Source: yannickcr/eslint-plugin-react

This example throws error Your render method should have return statement even though an element is being returned.

class Header extends React.Component {
  render() {
    const { text, headerType } = this.props;

    switch (headerType) {
      case 'h1':
        return <h1 className="large-header">{text}</h1>;
      case 'h2':
        return <h2 className="med-header">{text}</h2>;
      default:
        return <h3 className="sm-header">{text}</h3>;
    }
  }
}
bug

All 5 comments

If the return is wrapped in an if statement then it also doesn't work:

render() {
        var test = true;

        if (test) {
            return <div></div>;
        }
        else {
            return <div></div>;
        }
    }

I tried to fix this in https://github.com/jseminck/eslint-plugin-react/commit/2a51f2399df3424411543d38c41f8bf3bac10253 and https://github.com/jseminck/eslint-plugin-react/commit/0bf8e3f57bdd2e245da4e0c64f9c1385e5dd5f24

It now works with switch and if statements. I also added tests for a nested if and switch statement.

Additionally added another commit that makes sure that every child of the if and switch statements has a return statement:

@yannickcr @ljharb would be good if any of you could take a look at the code as I'm not really all that familiar with ASTs. It was quite challenging (but definitely a fun exercise).

The tests look good (although the error messages could be more helpful/tailored to the error condition) - I'm not up to the task of reviewing the AST stuff.

I'll look at improving the error message(s) and documentation and then make a PR.

Also I ran into the same issue reported in https://github.com/yannickcr/eslint-plugin-react/issues/542 already, e.g. that render() methods in classes that do not extend React.Component also are linted. Perhaps I'll have a look at that too as it is also stopping us from being able to use this rule.

Thanks for the details and the fix, but I rewrote the rule to use the component detection and fix #542 at the same time.

Was this page helpful?
0 / 5 - 0 ratings