I have 3 routes which render the same component<MainContainer/>, I want state to change inside those components based on the location.
Routes:
import React from 'react'
import { browserHistory, HashRouter, Route, Switch } from 'react-router-dom'
import { MainContainer } from '../containers'
import { LoginContainer } from '../containers'
const Routes = () => {
return (
<HashRouter history={ browserHistory }>
<Switch>
<Route exact={ true } path="/" component={ LoginContainer }/>
<Route exact={ true } path="/dashboard" component={ MainContainer }/>
<Route exact={ true } path="/dashboard/services" component={ MainContainer }/>
<Route exact={ true } path="/dashboard/users" component={ MainContainer }/>
</Switch>
</HashRouter>
);
}
export default Routes
The problem is that the componentDidMount only fires once, and does not fire again when the path is changed:
How would detecting the state of the route be achieved in React using the hashRouter?
Sidebar
import React from 'react'
import { withRouter } from 'react-router-dom'
class Sidebar extends React.Component {
constructor(props) {
super(props);
this.state = {}
this.navigate = this.navigate.bind(this);
}
navigate(path) {
this.props.history.push(`/dashboard/${path}`);
}
render () {
return (
<aside className="sidebar">
<div>
<h1>Main</h1>
<ul>
<li onClick={ () => this.navigate('services')}>Services</li>
<li onClick={ () => this.navigate('users')}>Users</li>
</ul>
</div>
</aside>
)
}
}
export default withRouter(Sidebar)
MainContainer
import React, { Component } from 'react'
import { connect } from 'react-redux'
import store from '../../store'
import * as firebase from 'firebase'
// Components
import { Sidebar } from '../../components'
import { Header } from '../../components'
// Containers
import UserListContainer from '../Users/UserListContainer'
import Body from './Body'
// Actions
import { addCurrentUser, searchUser, usersService, servicesService } from '../../actions'
export class Main extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
firebase.auth().onAuthStateChanged((user) => {
this.checkAuth();
});
}
checkAuth() {
const user = firebase.auth().currentUser;
this.props.addCurrentUser(user.email);
}
render() {
return (
<main>
<Header currentUser={ this.props.currentUser }/>
<section className="main-body">
<Sidebar />
<Body service={this.props.service}/>
</section>
</main>
)
}
}
const mapStateToProps = (state) => {
return {
service: state.globalReducer.service,
currentUser: state.globalReducer.currentUser
}
}
const mapDispatchToProps = (dispatch) => {
return {
searchUser: (user) => { dispatch(searchUser(user)) },
addCurrentUser: (user) => { dispatch(addCurrentUser(user)) },
usersService: () => { dispatch(usersService()) },
servicesService: () => { dispatch(servicesService()) }
}
}
const MainContainer = Main;
export default connect(mapStateToProps, mapDispatchToProps)(MainContainer)
