0

I'm trying to change the URL programmatically.

The URL is changed but the page doesn't refresh/render. I have tried to find the right answer for more than 2 hours but didn't succeed. I see that the URL indeed changed but the component wasn't refreshed. My Layout component looks like this:

export default class Layout extends Component {

public render() {

return (
  <BrowserRouter>
    <section className="layout">

      <header>
        <Header />
      </header>

      <main>
        <Switch>
          <Route path="/login" component={Login} exact />
          <Route path="/register" component={Register} exact />
          <Route path="/home" component={Main} exact />
          <Redirect from="/" to="/home"></Redirect>
        </Switch>
      </main>

      <footer>
        <Footer />
      </footer>

    </section>
  </BrowserRouter>
  );

 }
}

My Main component looks like this:

import React, { Component } from "react";
import './main.css'
import history from 'history/browser';

interface MainProps {

registerButton: string,
loginButton: string;
 }

export default class Main extends Component<MainProps, any>{

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

public render() {
    return (
        <div className="main">This is the Main Section
            <div>
                <button onClick={this.onRegisterButtonClicked}>REGISTER</button>
                <button onClick={this.onLoginButtonClicked}>LOGIN</button>
            </div>
        </div>);
}

private onLoginButtonClicked = () => {
history.push('/login');
 
}

private onRegisterButtonClicked = () => {
   
    
}
}

1 Answers1

0

OK!

I have tried to remove the interface (just to extends the component without props)

export default class Main extends Component<any>

and then the command: "this.props.history...." was recognized.

Soooooo I understood that if I want to implement my own props I have to add to the interface another field:

interface MainProps {
    history: BrowserHistory // This is the most important think
    registerButton: string,
    loginButton: string;
}

and then everything worked:

export default class Main extends Component<MainProps>{

private onRegisterButtonClicked = () => {
       
        this.props.history.push('/register');
    }
}