0

Need the ability to navigate without page reload.

For example from some place in code by clicking button or link

export default class Test1 extends React.Component {

    constructor(props) {
        super(props);

        this.onClick = this.onClick.bind(this);
    }

    onClick() {
        this.props.history.push('/my-path')
    }

    render() {
        return (
            <a className={this.props.className} onClick={this.onClick}>{this.props.children}</a>
            <input type="button" onClick={this.onCLick} value="halo2"/>
        );
    }

}

but this.props.history is undefined.

Things like

export default withRouter(Test1);

produce an error

Error: Invariant failed: You should not use <withRouter(Test1) /> outside a <Router>

Most positive effect reached with creating additional history class like here How to get history on react-router v4?

But it only change URL without actually moving to that location(does not render and does not executes expected events).

UPDATE 1

even tried push history to global variable

class DebugRouter extends BrowserRouter {
    constructor(props) {
        super(props);
        App.history = this.history;

and than

App.history.push('/my path');

It also only change URL. No changes to the page and events

Subdigger
  • 2,166
  • 3
  • 20
  • 42

1 Answers1

0

I usually use for that Link from 'react-router-dom'.

So you can just change <a> to <Link to='/path'>Text</Link>

Also make sure that your whole app is inside of provider <BrowserRouter> otherwise none of it will work.

Here is usefull link how to use it: https://reactrouter.com/web/guides/quick-start

Dima Malko
  • 227
  • 2
  • 19