0

I am doing routing on button click event

  redirect(){

       return <Redirect to='/chat' />;

    }

Its not working.

my home page- base component:

import React, { Fragment } from 'react';

  render() {

    const { value } = this.state;

    return (


        <Router>

          <div>
             <Switch>
            <Route exact={true} path="/" component={Home} />
            <Route path="/notify" component={Notify} />
            <Route path="/chat" component={Chat}/>
</Switch>

          </div>
          <footer className="foot">
            <BottomNavigation className="navbar navbar-default navbar-static-bottom navbar-fixed-bottom" value={value} onChange={this.handleChange} className={this.props.root}>

                <div className="navi">
                  <Link   to="/"> <BottomNavigationAction label="Home" value="Home" icon={<HomeIcon />} /></Link>
                </div>
                <div  className="navi">
                <Link to="/notify"><BottomNavigationAction label="Notification" value="Notification" icon={<NotifyIcon />} /></Link>
                </div>
                <div className="navi">
                <Link to="/chat"> <BottomNavigationAction label="Listen" value="Listen" icon={<LocationOnIcon />} /></Link>
                </div>

            </BottomNavigation>
          </footer>

From my child component I have to redirect to another component, here is my child component:

  <IconButton className={this.props.iconButton} aria-label="Search" onClick={this.redirect}>
        <SearchIcon />
      </IconButton>

redirect(){

       return <Redirect to='/chat' />;

    }

So but I am not getting any console error too.

Sridhar Paiya
  • 438
  • 1
  • 6
  • 25
  • its because `Redirect` is a ui element, you have to render that and onClick is an event handler it will not render anything, it will simply execute the body of the handler function. To solve your issue, use `this.props.history.push('/chat')` – Mayank Shukla May 28 '19 at 05:12

1 Answers1

4

<Redirect /> is a component. So, you should use it like this.

class App extends React.Component{
  state = { 
    isRedirect: false,
  }

  redirect = () => {
    this.setState({ isRedirect: true });
  }

  render() {
    return (
      <>
        <button onclick={this.redirect}> Redirect</button>

        {this.state.isRedirect ? <Redirect to="/" /> : null }
      </>
    ) 
  }

}

OR

You can use history API

but you should add withRouter()

class App extends React.Component{
  render(){
    return(
      <>
        <button onClick={()=>{this.props.history.push('/')}}>Redirect</button>
      </>
    )
  }
}

export default withRouter(App);

kyun
  • 7,487
  • 4
  • 21
  • 44