Return A Value From A React render
ID |
javascript.react_render_return |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
react, reliability |
Description
Reports a class component’s render() that returns no value on some path: it has no
value-returning return at all, or it contains a bare return;.
Rationale
render() is the one method React calls for its result. A method that falls off its end returns
undefined, and React refuses it with "Nothing was returned from render" rather than rendering
nothing — so the component does not degrade, it takes the tree down with it.
The intended "render nothing" is return null, which React accepts and which says so.
A bare return; is the same defect written differently, and the more common one: it appears as an
early exit copied from an event handler, where returning nothing is exactly right. It is reported
even when the other paths do return markup, because that one path still throws. The method rather
than the statement carries the issue, which keeps it to one per broken component.
Only a class extending React’s component base is judged — Component or PureComponent, however
it is imported or qualified — because render is an ordinary method name elsewhere. A returning
statement counts only when the method itself is the function enclosing it, so a return inside a
callback in the body does not answer for the method. A render() that throws instead of returning
is left alone: an abstract base component does that deliberately. A render = () ⇒ … class field
is a different node and is not covered, since the arrow form returns its body and the defect cannot
be written that way.
import React from "react";
class SilentPanel extends React.Component {
render() { // FLAW - falls off the end
const rows = this.props.rows;
}
}
class EarlyExitPanel extends React.Component {
render() { // FLAW - one path returns nothing
if (!this.props.rows) {
return;
}
return <List rows={this.props.rows} />;
}
}
class Panel extends React.Component {
render() {
if (!this.props.rows) {
return null; // OK - null renders nothing, by design
}
return <List rows={this.props.rows} />;
}
}