DEV Community

devterminal
devterminal

Posted on

4 3

Self-invoking function as React children

I always wanted to be able to use return statement on children rendering. Self-Invoking Function is the solution. This is an example of building page states inside of the Layout component. 💡🧑‍💻

const SelfInvokingChildren = () => {
  const [loading, error, data] = useData()

  return (
    <Layout>
      {(function () {
        if (loading) return <Placeholder />

        if (error) return <Error />

        if (!data) return <NotFound />

        return <PageContent data={data} />
      })()}
    </Layout>
  )
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more