reactjs / react-router-tutorial

5.52k stars 1.75k forks source link

Using browserHistory from both 'react-router' and 'react-router/lib/browserHistory' doesn't update component #301

Closed brotzky closed 7 years ago

brotzky commented 7 years ago

If you're importing browserHistory differently than how you declare it in your Router history={browserHistory} it will not work properly. I'm not sure if this is intended, but it caused me a few headaches. I've created some examples to help demonstrate. The URL pathname gets updated but the components don't.

Examples

// App.js

import React from 'react';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router'; // notice I'm importing from 'react-router'
import routes from '../../../routes';

export default function App(props) {
  return (
    <Provider store={props.store}>
        <Router history={browserHistory} routes={routes} />
    </Provider>
  );
}

Working case:

// Button.js

import React from 'react';
import { browserHistory } from 'react-router'; // importing from 'react-router'

function handelClick() {
  // this works. path updates and renders new component
  browserHistory.push('/my/path/name');
}

const Button = () => <button onClick={handleClick}>Update Route</button>;

Broken case:

// Button.js

import React from 'react';
import browserHistory from 'react-router/lib/browserHistory'; // <-- NOT from 'react-router' like in App.js Router

function handelClick() {
  // this DOES NOT work, only URL pathname is updated correctly.
  browserHistory.push('/my/path/name');
}

const Button = () => <button onClick={handleClick}>Update Route</button>;

āœ…

import { Router, browserHistory } from 'react-router';
+
import { browserHistory } from 'react-router';

āœ…

import { Router } from 'react-router';
import browserHistory from 'react-router/lib/browserHistory';
+
import browserHistory from 'react-router/lib/browserHistory';

šŸ™…

import { Router } from 'react-router';
import browserHistory from 'react-router/lib/browserHistory';
+
import { browserHistory } from 'react-router';

šŸ™…

import { Router, browserHistory  } from 'react-router';
+
import browserHistory from 'react-router/lib/browserHistory';
brotzky commented 7 years ago

It appears I've made this in the wrong repo. Sorry!

himanshujariyal commented 7 years ago

Find the issue here: https://github.com/ReactTraining/react-router/issues/4640

arseniy-poltev commented 6 years ago

You can install react-router using npm install react-router@3 It occur when npm install react-router command.

ahtashamabbasse commented 5 years ago

Thank you @brotzky for your explanation.