After pushing to history in React, the rendered component fails to display on the screen

I am in the process of developing a React application. Here are the dependencies I am currently using:

"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-helmet": "^6.1.0",
"react-router": "^5.0.1",
"react-router-dom": "^5.0.1",

(I am also incorporating SemanticUI as my UI framework)

This is how I have initialized the application:

export const startup = async () => {
    const history: History = createBrowserHistory();
    const rootStore: RootStore = await RootStore.build(history);
    const app = <App history={history} rootStore={rootStore}/>;
    return { rootStore, app }
}

I have three components set up:

  1. The Index component:
startup().then(x => {
    const root = document.getElementById('root');
    console.log(x);
    const history = x.rootStore.history;

    reactRender(
        <>

            <BrowserRouter>
                <Provider history={x.rootStore.history} rootStore={x.rootStore}>
                    <Router history={history}>
                        <Route exact path='/' component={HomePage}/>
                        <Route exact path='/about' component={AboutComponent}/>
                    </Router>
                </Provider>
            </BrowserRouter>

        </>,
        root
    );
}).catch(e => {
    console.log(e);
    alert('Unable to initialize the application')
})
  1. The Home page component:
export interface HomePageProps {
    rootStore?: RootStore;
}

class HomePage extends React.Component<HomePageProps> {

    public constructor(props: HomePageProps) {
        super(props);
    }

    public render() {
        return (
            <>
                <h2>Home</h2>
                <Button onClick={this.handler}>
                    Go to about
                </Button>
            </>
        )
    }

    public handler = () => {
        this.props.rootStore?.history!.push('/about');
        console.log(this.props.rootStore?.history);
    }

}

export default inject('rootStore')(observer(HomePage))
  1. The About component:
export interface AboutComponentProps {
    rootStore?: RootStore;
}

class AboutComponent extends React.Component<AboutComponentProps> {
    public constructor(props: AboutComponentProps) {
        super(props);
    }

    public render() {
        return (
            <>
                <h2>About</h2>
                <Button onClick={this.handler}>
                    Go to home
                </Button>
            </>
        );
    }

    public handler = () => {
        this.props.rootStore?.history!.push('/');
    }
}
export default inject('rootStore')(observer(AboutComponent))

After clicking "Go to home" or "Go to about", the URL changes in the browser address bar but the new component is not rendered. Is this a bug in the new version? Or is there a way to solve it?

P/S You can check this bug in CodeSandbox. https://codesandbox.io/s/gallant-gates-9gkuf

Answer №1

When creating an instance of history and utilizing the router component, there is no longer a need for excessive code. Here's an example:

Index component

const rootElement = document.getElementById('root');
ReactDOM.render(
  <StrictMode>
    <BrowserRouter>
      <Switch>
        <Route exact path="/home">
          <HomeComponent />
        </Route>
      </Switch>
    </BrowserRouter>
  </StrictMode>,
  rootElement
);

And here is a test component:

import React from 'react';
import { RouteComponentProps, withRouter } from 'react-router';

interface HomeProps extends RouteComponentProps {}

class HomeComponent extends React.Component<HomeProps> {
  public render() {
    return (
      <>
        <h1>Home page</h1>
        <button onClick={() => this.props.history.push('/component')}>
          Go to component
        </button>
      </>
    );
  }
}

export default withRouter(HomeComponent);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an obscure issue when using Discord.js v14 after attempting to cancel and resubmit a modal

I'm currently working on a Discord bot using modals in Discord.js v14. These modals appear after the user clicks a button, and an .awaitModalSubmit() collector is triggered to handle one modal submission interaction by applying certain logic. The .awa ...

"Encountering a 500 error on Chrome and Internet Explorer while trying to sign

I am currently working on an ASP.NET Core application that handles identity management through Azure AD B2C using the ASP.Net Core OpenID Connect. The front end is developed using AngularJS 2 with TypeScript. In my Logout function, the user is redirected t ...

Retrieve the text content from the HTML document

I'm facing a beginner's challenge. I have a div element and I want to extract the URL from the data-element attribute into a .json file Is there a way to do this? <div content="" id="preview" data-element="http://thereislink" class="sample ...

Exploring the functionality of the scan operator within switchMap/mergeMap in RxJS

We're utilizing the scan operator to handle our 'load more' button within our table. This operator allows us to accumulate new results with the previous ones, but we've come across some unexpected behavior. Let's break it down by l ...

Search through the directory of images and generate a JSON representation

I'm looking for a way to transform a URL-based directory of images into a Json object, which I can then utilize and connect within my Ionic project. Despite extensive searching, I have yet to find any satisfactory solutions to this challenge. Thus, I ...

Storing a variable in Cypress with Typescript for use in the afterEach teardown step

Throughout my test cases, I store data in a variable to be used consistently. The variable maintains its value until the very end of the test, but when trying to access it in the @afterEach teardown function for global clean up, it appears empty. It seems ...

What could be causing my for loop to not function properly within the ngOnInit lifecycle hook?

I am attempting to create a nested loop structure in order to access an array that is inside an object within an array of objects, and then store this data into a new array. My issue arises as the first loop executes successfully but the second one does no ...

What is the best way to initiate a refetch when the need arises to follow a different path?

I have encountered a situation where I am able to pass the refetch function on a child component. However, an issue arises when transitioning to another page and implementing redux. This is particularly problematic when attempting to open a dialog for a ne ...

Authorizer custom is not being triggered for websocket connection event

I'm currently working on implementing a custom authorizer for an API Gateway Websocket API. Below is my custom authorizer implementation using CDK: const authFunc = new lambda.Function(scope, utils.prefixed("WebsocketAuth"), { runtime: ...

Ways to resolve the issue of 'message' property lacking an initializer in TypeScript without suppressing errors

Currently, in the process of using TypeScript and Sequelize to create a model within Node.js. import { Table, Column, Model, AllowNull } from 'sequelize-typescript'; @Table class Person extends Model { @Column @AllowNull(false) name: strin ...

Unable to loop through the Array

let Users = [ { name: 'John', id: '1', jp: 'USA' }, { name: 'Jane', id: '2', jp: 'Japan' }, ]; export function DisplayUsers(usersList) { return ( <div> {usersList?.map((user ...

How to generate a SHA256 hash of the body and encode it in base64 using Python compared to

I'm aiming to hash the body using SHA256 and then encode it with base64. I'm in the process of converting my code from Python to TypeScript. From what I gathered via a Google search, it seems like crypto can be utilized instead of hashlib and ba ...

What is the best method for loading resources from routes such as /page/:id/subpage and more?

The current structure of my app component is as follows: <app-navigation></app-navigation> <router-outlet></router-outlet> with defined routes: const appRoutes: Routes = [ { path: 'items', component: ListComponent }, ...

Unable to expand the dropdown button collection due to the btn-group being open

Having trouble with the .open not working in Bootstrap 4.3 after adding the btn-group class to open the dropdown... I am looking for a way to load the dropdown without using JavaScript from Bootstrap. This is the directive I am trying to use: @Host ...

Error encountered: "Unable to locate module 'typescript-Collections' when modifying the module to "umd" or "amd" in the tsconfig.json file."

I recently upgraded to VS17 Enterprise and encountered an issue when trying to import the TypeScript Collections library from GitHub. After following the instructions on their page, I realized that changing the module option in my tsconfig.json file to eit ...

What are the reasons behind memory leaks and decreased rendering speed when I exit and then reopen a React component (specifically Material-Table)?

I have been working on a basic React example for learning purposes, and I incorporated the use of material-table in one of my components. However, I noticed that each time I change pages and reopen the component (unmount and mount), the rendering speed of ...

The package.json entry for "abc-domains" is not functioning correctly even though it is set to "latest" version

Unique Scenario Imagine there's a package called xyz-modules that I've developed. The package.json file in my project looks like this: ... "devDependencies": { "@company/xyz-modules": "latest", ... } ... After ...

Cleaning up HTML strings in Angular may strip off attribute formatting

I've been experimenting and creating a function to dynamically generate form fields. Initially, the Angular sanitizer was removing <input> tags, so I discovered a way to work around this by bypassing the sanitation process for the HTML code stri ...

React hooks causing dynamic object to be erroneously converted into NaN values

My database retrieves data from a time series, indicating the milliseconds an object spends in various states within an hour. The format of the data is as follows: { id: mejfa24191@$kr, timestamp: 2023-07-25T12:51:24.000Z, // This field is dynamic ...

How can I resolve the infinite loop issue caused by Angular Auth guard when using routing?

My current struggle lies within the authentication guard logic and routing setup. In my app-routing.module.ts file, I have defined 3 routes: const routes: Routes = [ { path: '', loadChildren: () => import('./browse/browse.mod ...