menu
up-caret
down-caret

Reach

Accessible React

# General

General Chatter

Trending conversations
Google Analytics
@hellojere · 3d
React Suspense + lazy over Parcel.js
@david-gomez · 42d
Setting basepath="/path" in the Router doesn't do anything..
@oooooooooooooooooooo · 7d
How to use dialog with react-pose?
@darkeye · 36d
How to inspect the inside of the MenuList?
@jmarantz · 5d

React Suspense + lazy over Parcel.js

Reach/General · February 8, 2019 at 11:12pm

React Suspense + lazy over Parcel.js

February 8, 2019 at 11:12pm (Edited 1 month ago)

I'm trying to use React Suspense + lazy to dynamically import some components and assign its paths using the name of the component stored in a "config file" but I'm getting some errors and I think is because is not possible doing the way I'm trying to.

This is the code:

import React, { Suspense, lazy } from 'react';
import { render } from 'react-dom';
import { Router, Redirect } from '@reach/router';
import Layout from './containers/Layout';
import Header from './containers/Header';
import Navigation from './containers/Navigation';
import Content from './containers/Content';
import pages from './pages.json';
import 'normalize.css';
import './styles.css';
const Component = ({ component }) => {
const LazyComponent = lazy(() => import(`./components/${component}`));
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
};
const App = () => {
const pathname = window.location.pathname;
const defaultPath = '/';
const currentPath =
pathname !== defaultPath ? pathname.replace(defaultPath, '') : pathname;
const isInvalidPath = !pages.map(({ path }) => path).includes(currentPath);
return (
<Layout>
<Header />
<Navigation
items={pages}
initialPath={isInvalidPath ? defaultPath : currentPath}
/>
<Content>
<Router>
{isInvalidPath && (
<Redirect from={currentPath} to={defaultPath} noThrow />
)}
{pages.map(({ component, path }, idx) => (
<Component
key={idx}
component={component}
path={path}
default={pathname === defaultPath}
/>
))}
</Router>
</Content>
</Layout>
);
};
render(<App />, document.getElementById('app'));

I'm also trying using the Suspense component wrapping the map but I still get the same error I'm getting using the Suspense to wrap only the actual Component.

The error is:

Uncaught TypeError: Cannot read property 'substr' of undefined
at startsWith (utils.js:6)
at resolve (utils.js:143)
at index.js:454
at LocationProvider.render (index.js:127)
at finishClassComponent (react-dom.development.js:14391)
at updateClassComponent (react-dom.development.js:14346)
at beginWork (react-dom.development.js:15213)
at performUnitOfWork (react-dom.development.js:18780)
at workLoop (react-dom.development.js:18820)
at HTMLUnknownElement.callCallback (react-dom.development.js:149)

I'm just not sure what I'm doing wrong or if it is even possible to do what I want.

I appreciate any help.

No messages yet