HiveBrain v1.2.0
Get Started
← Back to all entries
patternreactCritical

Is it possible to return empty in react render function?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
functionrenderreturnreactemptypossible

Problem

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 ({this.props.children});
}


The problem is:

return (); // here has some syntax error

Solution

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:


{false}

{null}

{undefined}

{true}


Example:

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



const App = ({ number }) => {
if(number%2) {
return (

Number: {number}

)
}

return (null); //===> notice here, returning null for even values
}

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

ReactDOM.render(

{data.map(el => )}
,
document.getElementById('app')
)




Code Snippets

return (null);
<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

Context

Stack Overflow Q#42083181, score: 443

Revisions (0)

No revisions yet.