0

I have an uncontrolled link tag <a class="link" href="#">Click Me</a> I wish to use to invoke a route change in react.

// Slowly shifting from JQuery
$(".link").on("click", (evt) => {
    evt.preventDefault();
    var browserHistory = createBrowserHistory();        
    browserHistory.push('/detail/' + evt.target.dataset.id);

    // expect react-router to update view based on route change
    // ???
});

I would like to eliminate a full page reload if at all possible. Therefore, calling location.href="/detail/" or anything of similar nature I would like to avoid.

Does anyone know how do I accomplish this?

Jim
  • 443
  • 1
  • 5
  • 18
  • 1
    First of all you shouln't be using jquery with React, however you can refer this link https://stackoverflow.com/questions/44127739/programatically-routing-based-on-a-condition-with-react-router/44128108#44128108 – Shubham Khatri Jul 20 '17 at 14:46

1 Answers1

0

I found the solution (for me anyway). This turned out to be an issue with the way I was importing the history module into my app.

For reasons I'm not fully able to explain, creating a single history module to be referenced by the other modules in my application resolved this problem.

// history.ts
import createHistory from 'history/createBrowserHistory';
export default createHistory();

Apparently, when importing the history object across other modules, it doesn't reference the same object across these modules; or I was referencing it incorrectly. Each module was referencing a separate history object. This prevented the history.listen(...) (in one module) from detecting the history.push(...) in another module.

// app.tsx

/* FAILS: Creates multiple history objects across modules */
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();

/* SUCCEEDS: This creates a single history object shared across modules */
import history from './history';  // This works!
...
ReactDOM.render(
    <Router history={history}>
        <App.Frame>
        ...
        </App.Frame>
    </Router>
    , document.getElementById('root')
);
// config.ts

/* FAILS: Creates multiple history objects across modules */
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();

/* SUCCEEDS: This creates a single history object shared across modules */
import history from './history';  // This works!
...
$('.link').each((i, e) => {
    $(e).on("click", (evt) => {
        evt.preventDefault();
        history.push('/detail/' + evt.target.dataset.id);
    });
})

Credit to the following post that led me to the solution: Routing in React, the uncomplicated way

Jim
  • 443
  • 1
  • 5
  • 18