0

I went through the following questions.

Using React-Router with a layout page or multiple components per page Programmatically navigate using react router V4

Thanks to this, I got some idea which I applied in my case. I wanted App to get a layout to have logout option. The App component setup is like this:

<Router>
    <div>
        <header>
        <img className='logo' src={ImgName} alt="Img"></img>
        <ul className={logoutToggleClass} id="menulist-usrfolder">
            <li className='nav-li-folder'
                onClick={this.handleLogout}> 
                <span className='nav-links'
                id='logout-span'>LogOut</span>
            </li>
        </ul>
        </header>
        <Switch>
            <Route exact path = '/' render={()=> 
            <HomePage url = {apiUrl} handleLoginState={this.handleLoginState}
            handleLogoutState={this.handleLogoutState}
            historyToApp={this.historyToApp}
            />} />
            <Route exact path = '/user/folders' render = {() => 
            <UserFolder url={apiUrl}
            handleLoginState={this.handleLoginState}
            handleLogoutState={this.handleLoginState}
            historyToApp = {this.historyToApp}
            />} />
        </Switch>
    </div>
</Router>

handleLogoutState toggles the visibility of logout button. historyToApp is defined as the following:

historyToApp = (hist)=> {
    this.setState({history: hist})
}

This function is sent to components which are executed on ComponentDidMount

componentDidMount() {
    /* Other Stuff */
    this.props.historyToApp(this.props.history)
}

This state is being called by App on logout to push history to '/'

this.state.history.push('/')

This works

But I'm not sure if this is the right way. If there is a better solution, I would really appreciate it.

Ishan Tomar
  • 1,252
  • 1
  • 14
  • 19

0 Answers0