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.

1
  • 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') Commented May 28, 2019 at 5:12

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

I chose the history API method its working
@SridharPaiya I agree, history API is more recommendable

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.