Pass React Element to Library

I have an element whose id I’m passing to a library, but it takes time to perform the operations on the passed element. It currently looks like this:

  useEffect(() => {
    Promise.all(build("#el")).then(() => {
    ...
    })
  }, [])

  // build() is the function imported from an external library
  // which creates some sort of visualisation of element `el`
  return(
    <>
      <Component1 />
      <div id="el" />
      <Component />
    </>
  )

So I wanted to create a loader, that would run till the function is running, like so:

  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all(build("#el")).then(() => {
    ...
    }).finally(() => setLoading(false));
  }, [])

  if(loading) return <div>Loading...</div>

   return(
    <>
      <Component1 />
      <div id="el" />
      <Component />
    </>
  )

But the problem with this is that the external library is not able to find the element “el” because it doesn’t exist in the DOM till the point loading is false. It would work if I create the element directly in index.html but then, I would not be able to position this element.

Is there any way to achieve this?

Answer

Instead of an early return you could conditionally render the loader in addition to the empty #el div.

return(
  <>
    ... possibly other content

    {loading && <div>Loading...</div>)

    ... possibly other content

    {!loading && <Component1 />}

    <div id="el"></div>

    {!loading && <Component />}

    ... possibly other content
  </>
)

The gist is that you want the #el div rendered regardless of the loading state. The rest of the UI of this component can revolve around being conditionally rendered by the loading state if they need to be.