3

Its not the common dynamic loading question. In our project, we do have some js files (with component) on the server and we want to load those components dynamically in the react app.

I know about the import() but that takes a path of the file. In our case the file is with the server. Is there any way to achieve this.

File on the server Foo.js

import React from 'react'

export default function Foo() {
  return (
    <div>My Complex component</div>
  )
}

My React app

import React from "react";

export default function App() {
  const Component = fetchFooFromServer(); // how to do this
  return (
    <div>
      <Component></Component>
    </div>
  );
}

I am open to any suggestions. Using import(), React.Lazy etc.

targhs
  • 1,477
  • 2
  • 16
  • 29

1 Answers1

-3

Assuming Foo.js is in the same folder as your React app, you should be able to import the component like this:

import React from "react";
import Foo from "foo";

export default function App() {
  return (
    <div>
      <Foo></Foo>
    </div>
  );
}
Jay
  • 42
  • 4
  • sorry i just read your question more carefully. if it's a remote server you'll want to use a function like fetch() to grab it remotely – Jay Apr 28 '23 at 19:57
  • That's the issue @Jay. If i download the file from the server. How should i use it as a module? I can download the file content as string but that doesn't facilitate using it as a module, unless you know any other way. – targhs Apr 29 '23 at 17:41
  • so did you find any solution? – user1732457 Jun 13 '23 at 12:24