ccnokes
ccnokes

Reputation: 7105

Return null from a stateless component/"functional component"

I have a stateless functional component in React 0.14 that worked in React 0.13, but now returns the following error:

No render method found on the returned component instance: you may have forgotten to define render, returned null/false from a stateless component, or tried to render an element whose type is a function that isn't a React component.

This is my component:

function ToggleDisplay(props) {
    //should render a <noscript> per React's implementation
    if(props.if === false) {
        // return <noscript></noscript>; //do I have to do this manually now?
        return null;
    }

    let style = {};
    if(shouldHide(props)) {
        style.display = 'none';
    }
    return (
        <span style={style} {...props} />
    );
}

Do I have to manually return a <noscript> now? Is there another way to return null in stateless component?

Upvotes: 25

Views: 13953

Answers (2)

Andrew Patton
Andrew Patton

Reputation: 5404

As of React 15.0, you can return null from a stateless functional component. (See #5355). No more having to return <noscript /> 🎉


The change that made this possible is that React removed support for component classes that don’t inherit from React.Component, meaning they can reliably differentiate between React components (classes that inherit React.Component) and functional stateless components. So the PR to enable the functionality just involved removing and simplifying the code that instantiates the components.

Upvotes: 21

Ray Booysen
Ray Booysen

Reputation: 30021

Looks like not, this is a technical constraint in Javascript. To support arrow functions and plain functions as "components" React needs to know if we can call new on them.

We can call new on everything if they're plain functions as long as they return a ReactElement. However, that won't work for null/false/string return values and we want to support those too. We also can't call new on arrow functions. Likewise, we can't NOT call new on classes.

Relevant GitHub Issue

Upvotes: 13

Related Questions