Is it possible to return empty in react render function?

Reactjs

Reactjs Problem Overview


I have a notification component, and I have a timeout setting for it. After timeout I call this.setState({isTimeout:true}).

What I want to do is if already timeout, I want just render nothing:

render() {
  let finalClasses = "" + (this.state.classes || "");
  if (isTimeout){
    return (); // here has some syntax error
  }
  return (<div>{this.props.children}</div>);
}

The problem is:

> return (); // here has some syntax error

Reactjs Solutions


Solution 1 - Reactjs

Yes you can, but instead of blank, simply return null if you don't want to render anything from component, like this:

return (null);

Another important point is, inside JSX if you are rendering element conditionally, then in case of condition=false, you can return any of these values false, null, undefined, true. As per DOC:

> booleans (true/false), null, and undefined are valid children, > they will be Ignored means they simply don’t render.

All these JSX expressions will render to the same thing:

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

Example:

Only odd values will get rendered, because for even values we are returning null.

const App = ({ number }) => {
  if(number%2) {
    return (
      <div>
        Number: {number}
      </div>
    )
  }
  
  return (null);           //===> notice here, returning null for even values
}

const data = [1,2,3,4,5,6];

ReactDOM.render(
  <div>
    {data.map(el => <App key={el} number={el} />)}
  </div>,
  document.getElementById('app')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app' />

Solution 2 - Reactjs

Some answers are slightly incorrect and point to the wrong part of the docs:

If you want a component to render nothing, just return null, as per doc:

> In rare cases you might want a component to hide itself even though it > was rendered by another component. To do this return null instead of > its render output.

If you try to return undefined for example, you'll get the following error:

> Nothing was returned from render. This usually means a return > statement is missing. Or, to render nothing, return null.

As pointed out by other answers, null, true, false and undefined are valid children which is useful for conditional rendering inside your jsx, but it you want your component to hide / render nothing, just return null.

EDIT React 18:

React 18 will allow rendering undefined instead of throwing. See this announcement.

Solution 3 - Reactjs

Yes you can return an empty value from a React render method.

You can return any of the following: false, null, undefined, or true

According to the docs:

> false, null, undefined, and true are valid children. They > simply don’t render.

You could write

return null; or
return false; or
return true; or
return <div>{undefined}</div>; 

However return null is the most preferred as it signifies that nothing is returned

Solution 4 - Reactjs

Slightly off-topic but if you ever needed a class-based component that never renders anything and you are happy to use some yet-to-be-standardised ES syntax, you might want to go:

render = () => null

This is basically an arrow method that currently requires the transform-class-properties Babel plugin. React will not let you define a component without the render function and this is the most concise form satisfying this requirement that I can think of.

I'm currently using this trick in a variant of ScrollToTop borrowed from the react-router documentation. In my case, there's only a single instance of the component and it doesn't render anything, so a short form of "render null" fits nice in there.

Solution 5 - Reactjs

If you are using Typescript and your component/function has return type React.Element, you will get the following error.

> Type 'null' is not assignable to type 'ReactElement JSXElementConstructor>'.

The solution is React.Fragment.

return <React.Fragment />

or

return <></>

Solution 6 - Reactjs

for those developers who came to this question about checking where they can return null from component instead of checking in ternary mode to render or not render the component, the answer is YES, You Can!

i mean instead of this junk ternary condition inside your jsx in render part of your component:

// some component body
return(
  <section>
   {/* some ui */}
   
   { someCondition && <MyComponent /> }
   or
   { someCondition ? <MyComponent /> : null }

   {/* more ui */}
  </section>
)

you can check than condition inside your component like:

const MyComponent:React.FC = () => {
  
  // get someCondition from context at here before any thing


  if(someCondition) return null; // i mean this part , checking inside component! 
  
  return (
    <section>   
     // some ui...
    </section>
  )
}

Just Consider that in my case i provide the someCondition variable from a context in upper level component ( for example, just consider in your mind ) and i don't need to prop drill the someCondition inside MyComponent.

Just look how clean view your code gets after that, i mean you don't need to user ternary operator inside your JSX, and your parent component would like below:

// some component body
return(
  <section>
   {/* some ui */}
   
   <MyComponent />

   {/* more ui */}
  </section>
)

and MyComponent would handle the rest for you!

Solution 7 - Reactjs

We can return like this,

return <React.Fragment />;

Solution 8 - Reactjs

Returning falsy value in the render() function will render nothing. So you can just do

 render() {
    let finalClasses = "" + (this.state.classes || "");
    return !isTimeout && <div>{this.props.children}</div>;
  }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionXinView Question on Stackoverflow
Solution 1 - ReactjsMayank ShuklaView Answer on Stackoverflow
Solution 2 - ReactjsjhujhulView Answer on Stackoverflow
Solution 3 - ReactjsShubham KhatriView Answer on Stackoverflow
Solution 4 - ReactjsChris KobrzakView Answer on Stackoverflow
Solution 5 - ReactjsFatih BulutView Answer on Stackoverflow
Solution 6 - ReactjsamdevView Answer on Stackoverflow
Solution 7 - Reactjssiluveru kiran kumarView Answer on Stackoverflow
Solution 8 - Reactjsschrodinger's codeView Answer on Stackoverflow