PropTypes not available after applying HOC - javascript

I recently built a components library but when I import my components my IDE doesn't show autocomplete props like other components do (based on propTypes) :
In my library, all components are exported with a HOC and I found out that by removing the HOC the props are now available in auto complete. Here's my HOC :
import * as React from 'react'
import hoistNonReactStatics from 'hoist-non-react-statics'
import PropTypes from 'prop-types'
import { defaultTheme } from '../styles/defaultTheme'
const withTheme = (WrappedComponent) => {
const ThemeContext = React.createContext(defaultTheme)
const Enhance = (props) => {
const { _reactThemeProviderForwardedRef, ...rest } = props
return (
<ThemeContext.Consumer>
{(theme) => (
<WrappedComponent
{...rest}
theme={theme}
ref={_reactThemeProviderForwardedRef}
/>
)}
</ThemeContext.Consumer>
)
}
Enhance.propTypes = {
_reactThemeProviderForwardedRef: PropTypes.any,
...WrappedComponent.propTypes,
}
const ResultComponent = React.forwardRef((props, ref) => (
<Enhance {...props} _reactThemeProviderForwardedRef={ref} />
))
ResultComponent.displayName = `withTheme(${
WrappedComponent.displayName || WrappedComponent.name
})`
return hoistNonReactStatics(ResultComponent, WrappedComponent)
}
export default withTheme
I'm probably doing something wrong in my withTheme but I cannot find out what.
Here is one of the components :
import React from 'react'
import { Text, StyleSheet, TextPropTypes } from 'react-native'
import PropTypes from 'prop-types'
import { buildStyleSheet } from '../util/style-helpers'
import { withTheme } from '../core/theming'
const CustomText = React.forwardRef((props, ref) => {
const { children, className = '', style, theme, ...others } = props
const customStyle = buildStyleSheet(className, 'text', theme)
return (
<Text
ref={ref}
style={StyleSheet.flatten([customStyle, style])}
{...others}
>
{children}
</Text>
)
})
const propTypes = {
children: PropTypes.any,
className: PropTypes.string,
theme: PropTypes.object.isRequired,
...TextPropTypes,
}
CustomText.displayName = 'CustomText'
CustomText.propTypes = propTypes
export default withTheme(CustomText)

Related

How to implement material-ui Snackbar as a global function?

I am creating my react app with material-ui Snackbar.
In my project I have a lot of components and don't want to insert <Snackbar/> in each of them.
Is there a way to create function that will show snackbar, then just import and use this function in each component?
Something like:
import showSnackbar from 'SnackbarUtils';
showSnackbar('Success message');
You have to do it in react way. You can achieve this by creating a Higher Order Component.
Create a HOC that returns a snackbar component along with the wrappedComponent
Create a function in that HOC which accepts message, severity (if you are using Alert like me), duration and sets the appropriate states which are set to the props of the snackbar. And pass that function as a prop to the wrappedComponent.
Finally import this HOC wherever you want to display a snackbar, pass your component in it and call the HOC function from the prop (this.prop.functionName('Hello there!')) in the event handler where you want to display a snackbar and pass in a message.
Check this out.
https://stackblitz.com/edit/snackbar-hoc?file=src/SnackbarHOC.js
extend it as a Hook, and then you can call it once and use state with effects to show:
import { useSnackbar } from 'notistack';
import IconButton from "#mui/material/IconButton";
import CloseIcon from "#mui/material/SvgIcon/SvgIcon";
import React, {Fragment, useEffect, useState} from "react";
const useNotification = () => {
const [conf, setConf] = useState({});
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const action = key => (
<Fragment>
<IconButton onClick={() => { closeSnackbar(key) }}>
<CloseIcon />
</IconButton>
</Fragment>
);
useEffect(()=>{
if(conf?.msg){
let variant = 'info';
if(conf.variant){
variant = conf.variant;
}
enqueueSnackbar(conf.msg, {
variant: variant,
autoHideDuration: 5000,
action
});
}
},[conf]);
return [conf, setConf];
};
export default useNotification;
Then you can use it:
const [msg, sendNotification] = useNotification();
sendNotification({msg: 'yourmessage', variant: 'error/info.....'})
Here is a sample code for fully working example using Redux, Material-ui and MUI Snackbar
import { random } from 'lodash'
import { Action } from 'redux'
import actionCreatorFactory, { isType } from 'typescript-fsa'
const actionCreator = actionCreatorFactory()
export type Notification = {
message: string
}
export type NotificationStore = Notification & {
messageId: number
}
export const sendNewNotification =
actionCreator<Notification>('NEW_NOTIFICATION')
const defaultState: NotificationStore = { message: '', messageId: 1 }
const reducer = (
state: NotificationStore = defaultState,
action: Action
): NotificationStore => {
if (isType(action, sendNewNotification)) {
const {
payload: { message }
} = action
return { message, messageId: random(0, 200000) }
}
return state
}
export default reducer
// useNotification to get state from Redux, you can include them into same file if you prefer
import { NotificationStore } from './notification'
export function useNotification(): NotificationStore {
return useSelector<NotificationStore>(
(state) => state.notification
)
}
// Notification React-component - Notification.tsx
import React, { useState } from 'react'
import Button from '#mui/material/Button'
import Snackbar from '#mui/material/Snackbar'
import IconButton from '#mui/material/IconButton'
import CloseIcon from '#mui/icons-material/Close'
type Props = {
message: string
}
export function Notification({ message }: Props): JSX.Element | null {
const [notiOpen, setNotiOpen] = useState(true)
if (!message) {
return null
}
return (
<Snackbar
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left'
}}
open={notiOpen}
autoHideDuration={10000}
onClose={() => setNotiOpen(false)}
message={message}
action={
<React.Fragment>
<Button
color="secondary"
size="small"
onClick={() => setNotiOpen(false)}
>
Close
</Button>
<IconButton
size="small"
aria-label="close"
color="inherit"
onClick={() => setNotiOpen(false)}
>
<CloseIcon fontSize="small" />
</IconButton>
</React.Fragment>
}
/>
)
}
// Main App.tsx to run my application
import { Notification } from "./Notification.tsx"
import { useDispatch } from 'react-redux'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
const App: React.FC<AppProps> = () => {
const dispatch = useDispatch()
const { message, messageId } = useNotification()
return (
<ThemeProvider theme={appTheme}>
<Router>
<Switch>
<Route path="/public/:projectId" component={ProjectPage} />
<Route path="/login" component={LoginPage} />
<Route render={() => <PageNotFound />} />
</Switch>
</Router>
<Notification key={messageId} message={message} />
</ThemeProvider>
)
}
export default App
// Usage of hook in application - FileSomething.tsx
import { useDispatch } from 'react-redux'
import { useEffect } from 'react'
import { sendNewNotification } from 'src/redux/notification'
export function FileSomething(): JSX.Element {
function sendNotification() {
dispatch(
sendNewNotification({
message: 'Hey, im a notification'
})
)
}
useEffect(() => {
sendNotification()
}, [])
return (
<div>Component doing something</div>
)
}

React useContext returns default values

I'm trying to create a darkmode library (named react-goodnight) based on https://github.com/luisgserrano/react-dark-mode.
This is where the context is created.
import React from 'react'
const ThemeContext = React.createContext({
theme: '',
toggle: () => {}
})
export default ThemeContext
This is my useDarkMode hook that get/sets the theme to localStorage.
import { useState, useEffect } from 'react'
const useDarkMode = () => {
const [theme, setTheme] = useState('light')
const setMode = (mode) => {
window.localStorage.setItem('theme', mode)
setTheme(mode)
}
const toggle = () => (theme === 'light' ? setMode('dark') : setMode('light'))
useEffect(() => {
const localTheme = window.localStorage.getItem('theme')
localTheme && setTheme(localTheme)
}, [])
return [theme, toggle]
}
export default useDarkMode
This is the index of my library (react-goodnight).
import React, { useContext } from 'react'
import { ThemeProvider } from 'styled-components'
import { GlobalStyles } from './globalStyles'
import { lightTheme, darkTheme } from './settings'
import ThemeContext from './themeContext'
import useDarkMode from './useDarkMode'
const Provider = ({ children }) => {
const [theme, toggle] = useDarkMode()
return (
<ThemeProvider theme={theme === 'light' ? lightTheme : darkTheme}>
<GlobalStyles />
<ThemeContext.Provider value={{ theme, toggle }}>
<button onClick={toggle}>Toggle</button>
{children}
</ThemeContext.Provider>
</ThemeProvider>
)
}
export const useDarkModeContext = () => useContext(ThemeContext)
export default Provider
And, in the end, this is my example app where I'm trying to use it.
import React from 'react'
import Provider, { useDarkModeContext } from 'react-goodnight'
const App = () => {
const { theme, toggle } = useDarkModeContext();
console.log(theme)
return (
<Provider>
<div>hey</div>
<button onClick={toggle}>Toggle</button>
</Provider>
)
}
export default App
The "Toggle" button in the library's index works fine but the one in my example app does not.
The useDarkModeContext() returns empty.
What could be the issue?
Thanks!
You are doing wrong
1st option
you can use react-goodnight provider with your index.js and use useDarkModeContext(), don't name your index.js Provider else you can not use Provider coming from react-goodnight
import Provider, { useDarkModeContext } from 'react-goodnight'
const Provider = ({ children }) => {
const [theme, toggle] = useDarkMode()
return (
<ThemeProvider theme={theme === 'light' ? lightTheme : darkTheme}>
<GlobalStyles />
<Provider>
<ThemeContext.Provider value={{ theme, toggle }}>
<button onClick={toggle}>Toggle</button>
{children}
</ThemeContext.Provider>
</Provider>
</ThemeProvider>
)
}
2nd Option
you are passing ThemeContext in your index.js so you can also access that in app.js
import React, { useContext } from 'react'
import ThemeContext from './themeContext'
const App = () => {
const theme = useContext(ThemeContext);
console.log(theme)
return (
<Provider>
<div>hey</div>
<button onClick={toggle}>Toggle</button>
</Provider>
)
}
export default App
The reason it's not working is because you are calling useContext in the very same place where you print Provider.
Why is that wrong? Because useContext looks for parent context providers. By rendering Provider in the same place you call useContext, there is no parent to look for. The useContext in your example is actually part of App component, who is not a child of Provider.
All you have to do is move the button outside of that print, to its own component, and only there do useContext (or in your case the method called useDarkModeContext.
The only change would be:
import React from 'react'
import Provider, { useDarkModeContext } from 'react-goodnight'
const App = () => {
return (
<Provider>
<div>hey</div>
<ToggleThemeButton />
</Provider>
)
}
export default App
const ToggleThemeButton = () => {
const { theme, toggle } = useDarkModeContext();
return (
<button onClick={toggle}>Switch Theme outside</button>
);
};

Redux Connect w/ HOC - TypeError: Cannot set property 'props' of undefined

I'm building a quick authentication higher order component in Next.js and am getting some problems with the following code:
import SignIn from "../components/sign-in";
import { connect } from "react-redux";
import { useRouter } from "next/router";
const AuthenticationCheck = WrappedComponent => {
const { isAuthenticated, ...rest } = props;
const router = useRouter();
const protectedPages = ["/colours", "/components"];
const pageProtected = protectedPages.includes(router.pathname);
return !isAuthenticated && pageProtected ? (
<SignIn />
) : (
<WrappedComponent {...rest} />
);
};
function mapStateToProps(state) {
return {
isAuthenticated: state.auth.isAuthenticated
};
}
export default connect(mapStateToProps)(AuthenticationCheck);
If I change the code to remove redux & connect, it looks like this, and works perfectly.
const AuthenticationCheck = WrappedComponent => {
const { ...rest } = props;
const router = useRouter();
const protectedPages = ["/colours", "/components"];
const pageProtected = protectedPages.includes(router.pathname);
return pageProtected ? <SignIn /> : <WrappedComponent {...rest} />;
};
export default AuthenticationCheck;
I've been reading every SO, redux documentation etc for the last couple of hours, and I can't really find anything that matches what I'm doing, although I can't believe it's an uncommon use case.
Am I missing something obvious?
Solution: (Thankyou Dima for your help!)
So the final code that ended up working is:
import SignIn from "../components/sign-in";
import { connect } from "react-redux";
import { useRouter } from "next/router";
import { compose } from "redux";
const AuthenticationCheck = WrappedComponent => {
const authenticationCheck = props => {
const { isAuthenticated, ...rest } = props;
const router = useRouter();
const protectedPages = ["/colours", "/components"];
const pageProtected = protectedPages.includes(router.pathname);
return !isAuthenticated && pageProtected ? (
<SignIn />
) : (
<WrappedComponent {...rest} />
);
};
return authenticationCheck;
};
function mapStateToProps(state) {
return {
isAuthenticated: state.auth.isAuthenticated
};
}
export default compose(connect(mapStateToProps), AuthenticationCheck);
This works perfectly! 🙂
connect expects to get React component as a last argument, but you are sending HOC instead. You need to put connect and wrapper inside compose function. See below
import React from 'react'
import {compose} from 'redux'
import {connect} from 'react-redux'
import {doSomething} from './actions'
const wrapComponent = Component => {
const WrappedComponent = props => {
return (
<Component {...props} />
)
}
return WrappedComponent
}
const mapStateToProps = state => {
return {
prop: state.prop,
}
}
export default compose(
connect(mapStateToProps, {doSomething}),
wrapComponent
)
And the useit like this.
import React from 'react'
import withWrapper from 'your/path'
const Component = props => 'Component'
export default withWrapper(Component)

Export named arrow function got "Object(...) is not a function" error

In a React app I wrote a function in file1.js and use this function in file2.js
// file1.js
export const withPrefix = (Component) => (props) => (
<PrefixContext.Consumer>
{prefix => <Component {...props} prefix={prefix}/>}
</PrefixContext.Consumer>
)
// file2.js
import { withPrefix } from '/path/to/file1.js'
let Toolbar = withPrefix(({prefix}) => ( // !error happens here
<Fragment>
<div style={{flexGrow: 1}}>
<Button><Link to={`${prefix}/create`}>New Artifact</Link></Button>
</div>
<Search style={{width: 200}}/>
</Fragment>
))
Then I got the error "TypeError: Object(...) is not a function". So I changed export withPrefix function
export function withPrefix(Component) {
return (props) => (
<PrefixContext.Consumer>
{prefix => <Component {...props} prefix={prefix}/>}
</PrefixContext.Consumer>
)
}
And the error is gone, everything works. But I wonder why these two exports result differently?
And another question is if I want to export an arrow function in es6, is the 2nd export function style the only method?
Attachment 1 (DefaultView.js):
import React, {Component} from 'react'
import {Layout} from 'antd'
import Toolbar from './Toolbar'
import Content from './Content'
export const PrefixContext = React.createContext()
export function withPrefix(Component) {
return (props) => (
<PrefixContext.Consumer>
{prefix => <Component {...props} prefix={prefix}/>}
</PrefixContext.Consumer>
)
}
export default class DefaultView extends Component {
constructor(props) {
super(props)
this.state = {
view: props.defaultView
}
}
handleViewChange = (view) => {
this.setState({view})
}
render() {
const {prefix, views} = this.props
const {view} = this.state
return (
<PrefixContext.Provider value={prefix}>
<Layout>
<Toolbar view={view} views={views} onViewChange=
{this.handleViewChange}/>
<hr/>
<Content view={view}/>
</Layout>
</PrefixContext.Provider>
)
}
}
Attachment 2 (Summary.js)
import React, {Component, Fragment} from 'react'
import {Button, Input} from 'antd'
import {Link} from 'react-router-dom'
import ArtifactTable from './ArtifactTable'
import {withPrefix} from "./DefaultView"
const {Search} = Input
export const Toolbar = withPrefix(({prefix}) => (
<Fragment>
<div style={{flexGrow: 1}}>
<Button><Link to={`${prefix}/create`}>新建软件包</Link></Button>
</div>
<Search style={{width: 200}}/>
</Fragment>
))
class Summary extends Component {
state = {
data: []
}
componentDidMount() {
const {prefix} = this.props
console.log('prefix=' + prefix)
fetch(prefix).then(json => {
this.setState({data: json.content})
})
}
render() {
const {data} = this.state
return (
<div>
<ArtifactTable data={data}/>
</div>
)
}
}
export default withPrefix(Summary)
Attachment 3 (Toolbar.js)
import React from 'react'
import {Switch, Route} from 'react-router-dom'
import {Toolbar as SummaryToolbar} from './Summary'
import Create from './Create'
import Details from './Details'
import Edit from './Edit'
import {withPrefix} from "./DefaultView"
const Toolbar = withPrefix(({prefix, view, onViewChange}) => (
<div style={{background: '#fff', padding: 16, display: 'flex',
alignItems: 'baseline'}}>
<Switch>
<Route exact path={`${prefix}`} component={SummaryToolbar}/>
<Route exact path={`${prefix}/create`}
component={() => <Create.Toolbar view={view} onViewChange=
{onViewChange}/>}/>
<Route exact path={`${prefix}/:id`}
component={() => <Details.Toolbar view={view} onViewChange=
{onViewChange}/>}/>
<Route exact path={`${prefix}/:id/edit`}
component={() => <Edit.Toolbar view={view} onViewChange=
{onViewChange}/>}/>
</Switch>
</div>
))
export default Toolbar
Update It's indeed the cyclic dependency problem as #Bergi and #loganfsmyth said. After I moved out
the withPrefix export snippet into a new file Context.js from DefaultView.js, the problem resolved. But I still have one quesion. In a cyclic dependency circumstances, why export const f = () => () => {} different from export function f() => { return () => {} }. Is export const lazy evaluated than export function as #loganfsmyth said?

React-Router v4 rendering wrong component but matching correctly

I've got a sidebar with two buttons, 'test' and 'about'. Test (rocket icon) is rendered at '/test', and About (home icon) is rendered at '/'.
They're both located at the root of the app and are nested within a component.
When I start at '/' and click the Link to="/test" it always loads the 'About' component, and when I check the props for the componentDidMount of 'About', the match object contains match data for "/test".
Only when I refresh does it render the proper component, 'Test', again. Any idea why this is happening?
AppRoutes.js:
export class AppRoutes extends React.Component {
render() {
return (
<div>
<Switch>
<Route
exact path="/"
render={(matchProps) => (
<LazyLoad getComponent={() => import('pages/appPages/About')} {...matchProps} />
)}
/>
<Route
path="/login"
render={(matchProps) => (
<LazyLoad getComponent={() => import('pages/appPages/Login')} {...matchProps} />
)}
/>
<Route
path="/register"
render={(matchProps) => (
<LazyLoad getComponent={() => import('pages/appPages/Register')} {...matchProps} />
)}
/>
<Route
path="/test"
render={(matchProps) => (
<LazyLoad getComponent={() => import('pages/appPages/Test')} {...matchProps} />
)}
/>
...
AboutPage.js && TestPage.js (duplicates except for component name):
import React from 'react';
import SidebarContainer from 'containers/SidebarContainer';
import SidebarPageLayout from 'styles/SidebarPageLayout';
export const About = (props) => {
console.log('About Loading: ', props);
return (
<SidebarPageLayout>
<SidebarContainer />
<div>About</div>
</SidebarPageLayout>
);
}
export default About;
SidebarContainer.js:
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import Sidebar from 'sidebar/Sidebar';
import HamburgerButton from 'sidebar/HamburgerButton';
import AboutButton from 'sidebar/AboutButton';
import ProfileButton from 'sidebar/ProfileButton';
import TestButton from 'sidebar/TestButton';
export class SidebarContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
sidebarIsOpen: false,
sidebarElements: [],
};
}
componentDidMount() {
if (!this.props.authenticated) {
this.setState({
sidebarElements: _.concat(this.state.sidebarElements, HamburgerButton, ProfileButton, AboutButton, TestButton),
});
}
}
toggleSidebarIsOpenState = () => {
this.setState({ sidebarIsOpen: !this.state.sidebarIsOpen });
}
render() {
const { authenticated, sidebarIsOpen, sidebarElements} = this.state;
return (
<div>
<Sidebar
authenticated={authenticated}
sidebarIsOpen={sidebarIsOpen}
sidebarElements={_.isEmpty(sidebarElements) ? undefined: sidebarElements}
toggleSidebarIsOpenState={this.toggleSidebarIsOpenState}
/>
</div>
);
}
}
SidebarContainer.propTypes = {
authenticated: PropTypes.bool,
};
export default SidebarContainer;
Sidebar.js:
import React from 'react';
import _ from 'lodash';
import PropTypes from 'prop-types'
import SidebarStyles from '../styles/SidebarStyles';
export const Sidebar = (props) => {
if (props && props.sidebarElements) {
return (
<SidebarStyles sidebarIsOpen={props.sidebarIsOpen}>
{_.map(props.sidebarElements, (value, index) => {
return React.createElement(
value,
{
key: index,
authenticated: props.authenticated,
sidebarIsOpen: props.sidebarIsOpen,
toggleSidebarIsOpenState: props.toggleSidebarIsOpenState,
},
);
})}
</SidebarStyles>
);
}
return (
<div></div>
);
}
Sidebar.propTypes = {
authenticated: PropTypes.bool,
sidebarIsOpen: PropTypes.bool,
sidebarElements: PropTypes.array,
toggleSidebarIsOpenState: PropTypes.func,
};
export default Sidebar;
TestButton.js:
import React from 'react';
import PropTypes from 'prop-types';
import Icon from 'react-fontawesome';
import {
Link
} from 'react-router-dom';
export const TestButton = (props) => {
return (
<Link to="/test">
<Icon name='rocket' size='2x' />
</Link>
);
}
export default TestButton;
AboutButton.js:
import React from 'react';
import PropTypes from 'prop-types';
import Icon from 'react-fontawesome';
import {
Link
} from 'react-router-dom';
export const AboutButton = (props) => {
return (
<Link to="/">
<Icon name='home' size='2x' />
</Link>
);
}
export default AboutButton;
No refresh, just constant clicking on the '/test' route from the '/' route:
after refresh:
Edit:
Root components:
Edit:
store.js:
import {
createStore,
applyMiddleware,
compose,
} from 'redux';
import createSagaMiddleware from 'redux-saga';
import { rootReducer } from './rootReducers';
import { rootSaga } from './rootSagas';
// sagas
const sagaMiddleware = createSagaMiddleware();
// dev-tools
const composeEnhancers = typeof window === 'object' && (
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? (
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
) : compose
);
export function configureStore() {
const middlewares = [
sagaMiddleware,
];
const store = createStore(
rootReducer,
{},
composeEnhancers(applyMiddleware(...middlewares))
);
sagaMiddleware.run(rootSaga);
return store;
}
export const store = configureStore();
index.js (root):
import React from 'react';
import { Provider } from 'react-redux';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { store } from './store';
import AppContainer from 'containers/AppContainer';
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<AppContainer />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
AppContainer:
import React from 'react';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { logout, verifyToken } from './actions';
import { selectAuthenticated, selectAuthenticating } from './selectors';
import AppRoutes from 'routes/AppRoutes';
export class AppContainer extends React.Component {
constructor(props) {
super(props);
this.state = { loaded: false };
}
componentDidMount() {
const token = localStorage.getItem('jwt');
if (token) {
this.props.verifyToken(token, () => this.setState({ loaded: true }));
} else {
this.setState({ loaded: true });
}
}
render() {
if (this.state.loaded) {
return (
<AppRoutes
authenticated={this.props.authenticated}
authenticating={this.props.authenticating}
logout={this.props.logout}
/>
);
} else {
return <div>Loading ...</div>
}
}
}
function mapStateToProps(state) {
return {
authenticated: selectAuthenticated(state),
authenticating: selectAuthenticating(state),
};
}
function mapDispatchToProps(dispatch) {
return {
verifyToken: (token = '', callback = false) => dispatch(verifyToken(token, callback)),
logout: () => dispatch(logout()),
};
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(AppContainer));
Edit 2 for LazyLoad:
services/LazyLoad/index.js:
import React from 'react';
export class LazyLoad extends React.Component {
constructor(props) {
super(props);
this.state = {
AsyncModule: null,
};
}
componentDidMount() {
this.props.getComponent() // getComponent={() => import('./someFile.js')}
.then(module => module.default)
.then(AsyncModule => this.setState({AsyncModule}))
}
render() {
const { loader, ...childProps } = this.props;
const { AsyncModule } = this.state;
if (AsyncModule) {
return <AsyncModule {...childProps} />;
}
if (loader) {
const Loader = loader;
return <Loader />;
}
return null;
}
}
export default LazyLoad;
Your problem lies with LazyLoad component. For both "/" or "test" paths, what AppRoutes component ultimately renders is a LazyLoad component. Because Route and Switch just conditionally render their children. However, React can't differentiate "/" LazyLoad component and "/test" LazyLoad component. So the first time it renders LazyLoad component and invokes the componentDidMount. But when route changes, React consider it as a prop change of previously rendered LazyLoad component. So it just invokes componentWillReceiveProps of previous LazyLoad component with new props instead of unmounting previous one and mount a new one. That's why it continuously show About component until refresh the page.
To solve this problem, if the getComponent prop has changed, we have to load the new module with new getComponent inside the componentWillReceiveProps. So we can modify the LazyLoad as follows which have a common method to load module and invoke it from both componentDidMount and componentWillReceiveProps with correct props.
import React from 'react';
export class LazyLoad extends React.Component {
constructor(props) {
super(props);
this.state = {
AsyncModule: null,
};
}
componentDidMount() {
this.load(this.props);
}
load(props){
this.setState({AsyncModule: null}
props.getComponent() // getComponent={() => import('./someFile.js')}
.then(module => module.default)
.then(AsyncModule => this.setState({AsyncModule}))
}
componentWillReceiveProps(nextProps) {
if (nextProps.getComponent !== this.props.getComponent) {
this.load(nextProps)
}
}
render() {
const { loader, ...childProps } = this.props;
const { AsyncModule } = this.state;
if (AsyncModule) {
return <AsyncModule {...childProps} />;
}
if (loader) {
const Loader = loader;
return <Loader />;
}
return null;
}
}
export default LazyLoad;

Categories

Resources