How to return an empty jsx element from the render function in react?

Viewed 24669

I have a code in react that looks something like this:

class UserManagement extends React.Component {
    constructor() {
        super();
        this.state = {
            users: undefined,
        };
    }

    componentWillMount() {
        // load the users state with a Promise
        setTimeout(() => {
          this.setState({users: []});
        }, 800);
    }

    render() {
        if ( this.state.users === undefined ) {
            // until the users state is updated, I want to return an empty element
            return null;
        }

        // real site rendering
        return <div>We have users</div>;
    }
}

ReactDOM.render(
  <UserManagement />,
  document.getElementById("root")
);
<div>Will be blank at first while we don't have users, then show "We have users" after 800ms when we have users</div>
<div id="root"></div>
<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>

My question is: How to return an empty element until the users state is returned? I tried to return (null) as suggested in some places, but the browser raise this error:

Uncaught TypeError: Cannot read property 'style' of null

I am aware of the option to return (<div></div>), but I am not sure that this is the best practice in this case.

Thnaks!

7 Answers

Just in case anyone want another approach:

Since React v16.2 you can use Fragments allowing to add an empty JSX tag like this:

  return (
    <>
      <ChildA />
      <ChildB />
      <ChildC />
    </>
  );

Example extracted from official docs.

So in your case, returning a Fragment without any childs, works.

  return <></>;

You need to wrap it in a React.Fragment tag.

<React.Fragment></React.Fragment>

use the react Fragment <></>. One of its advantages is that it does not create additional Dom nodes into rendered component (such as an empty div tag).

You can use ternary condition to make your code more readable.

    render() {
        ( this.state.users === undefined ) ?
            return <></>   
        : return <div>We have users</div>;
    }

or oven simpler syntax would be

    render() {
        ( this.state.users) ?
            return <div>We have users</div>  
        : return <></>;
    }

I think you should add ternary operators like:

this.state.users? return null : return <div>We have user<\div>

One thing I did using React.useState was to initialize an empty JSX.Element object like so

const [jsxObject, setJsxObject] = React.useState(<></>);

Then, in whatever function you want to return a JSX.Element

setJsxObject(<h1>whatever inside</h1>);

Render it in the component

{jsxObject}
Related