import React from 'react';
import PropTypes from 'prop-types';
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
city: "Alwar",
}
}
componentDidMount(){
setInterval(()=>{
this.setState(()=>{
return { city: "Alwar"}
})
},2000)
}
render() {
console.log('Main Component render');
return (
<div>
<h2>
{this.state.title}
</h2>
<p>User Name: {this.props.name}</p>
<p>User Age: {this.props.age}</p>
</div>
);
}
}
Main.propTypes ={
name:PropTypes.string.isRequired,
age:PropTypes.number.isRequired
}
Main.defaultProps = {
name: 'Pankaj Kumar Choudhary',
age: 24
};
export default Main;
import { browserHistory } from 'react-router';
browserHistory.push('/some/path');
// history.js
import { createBrowserHistory } from 'history'
export default createBrowserHistory({
/* pass a configuration object here if needed */
})
// index.js
import { Router } from 'react-router-dom'
import history from './history'
import App from './App'
ReactDOM.render((
<Router history={history}>
<App />
</Router>
), holder)
// some-other-file.js
import history from './history'
history.push('/go-here')
import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
render () {
this.props.history;
}
}
withRouter(MyComponent);
import React from 'react';
import { withRouter } from 'react-router';
// variable which will point to react-router history
let globalHistory = null;
// component which we will mount on top of the app
class Spy extends React.Component {
constructor(props) {
super(props)
globalHistory = props.history;
}
componentDidUpdate() {
globalHistory = this.props.history;
}
render(){
return null;
}
}
export const GlobalHistory = withRouter(Spy);
// export react-router history
export default function getHistory() {
return globalHistory;
}
import getHistory from './history';
export const goToPage = () => (dispatch) => {
dispatch({ type: GO_TO_SUCCESS_PAGE });
getHistory().push('/success'); // at this point component probably has been mounted and we can safely get `history`
};
// then, in redux actions for example
import { push } from 'react-router-redux'
dispatch(push('/some/path'))