targhs
targhs

Reputation: 1805

Dynamically load components from server in React

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.

Upvotes: 3

Views: 199

Answers (1)

Jay
Jay

Reputation: 42

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>
  );
}

Upvotes: -3

Related Questions