Search code examples
htmlreactjssingle-spabase-path

How to add dynamic path to the single-spa-router path attribute in single spa react application


We have a code like this.

microfrontend-layout.html

<single-spa-router base="/">
  <main>
    <route default>
      <h1>404 route not defined</h1>
    </route>
</main>
</single-spa-router>

I would like to add a dynamic value to the 'base' attribute. How can we achieve this?


Solution

  • I was looking for the same solution, couldn't find it. But I kind of solved with "System.import" parcels based on window.location.

    mine is for tab UI, hope it helps

    import Parcel from "single-spa-react/parcel";
    const [parcels, setParcels] = useState(remoteHash);
        
          const updateParcelsWithModule = (module, endpoint) => {
            setParcels((prev) => {
              const newParcels = prev.map((parcel) => {
                if (parcel.endpoint === endpoint) {
                  return {
                    ...parcel,
                    module: module,
                    isRendered: true,
                  };
                }
                return parcel;
              });
              return newParcels;
            });
          };
        
          useLayoutEffect(() => {
            System.import("//localhost:9000/js/app.js")
              .then((module) => {
                updateParcelsWithModule(module, endpoint);
              })
              .catch((err) => console.error(err));
          }, [activeTabKey]);
        
          if (!parcels) return <></>;
        
          return (
            <div className="flex-auto h-0 overflow-auto">
          
              {parcels?.map((parcel) => (
                <div
                  key={parcel.endpoint}
                >
                  {parcel?.module && (
                    <Parcel
                      config={parcel?.module}
                      wrapWith="div"
                      wrapStyle={{ height: "100%" }}
                    />
                  )}
                </div>
              ))}
            </div>
          );
        };