React components should not be nested, as their state will be lost on each re-render of their parent component, possibly introducing bugs. This will also impact performance as child components will be recreated unnecessarily.
If the goal is to have the state reset, use a key instead of relying on a parent
state.
function Component() {
function NestedComponent() { // Noncompliant: NestedComponent should be moved outside Component
return <div />;
}
return (
<div>
<NestedComponent />
</div>
);
}
function Component() {
return (
<div>
<OtherComponent footer={ () => <div /> } /> { /* Noncompliant: Component is created inside prop */ }
</div>
);
}
class Component extends React.Component {
render() {
function UnstableNestedComponent() { // Noncompliant: NestedComponent should be moved outside Component
return <div />;
}
return (
<div>
<UnstableNestedComponent />
</div>
);
}
}
You should refactor your code to define a component independently, passing props if needed.
function OutsideComponent(props) {
return <div />;
}
function Component() {
return (
<div>
<OutsideComponent />
</div>
);
}
function Component() {
return <OtherComponent footer={ <div /> } />;
}
class Component extends React.Component {
render() {
return (
<div>
<OtherComponent />
</div>
);
}
}
Component creation is allowed inside component props when the prop name matches propNamePattern. Earlier versions only recognized prop
names starting with render. By default, the rule now accepts common render-prop naming conventions such as render*,
*Enhancer, and *Renderer. Make sure you are calling the prop in the receiving component and not using it as an element.
If a library uses different prop names for render props, configure propNamePattern to match them. Use allowAsProps only
when a name pattern is not precise enough and any prop may intentionally receive an inline component factory.
function OtherComponent(props) {
return <div>{props.renderFooter()}</div>;
}
function Component() {
return (
<div>
<OtherComponent renderFooter={() => <div />} />
</div>
);
}
function Button(props) {
return <div>{props.startEnhancer()}</div>;
}
function Component() {
return (
<div>
<Button startEnhancer={() => <Icon />} />
</div>
);
}