how to do dynamic routing in child component in reactjs?

258 views Asked by At

In my case, i have 6 menu in my application. In header part i have 'Next' and 'back' buttons. If i click next button, it should navigate to next menu, for back button, it should navigate to previous page. and header.js is a seperate component. Code is attached below

app.js

render() {
        return (
            <Router>
                <div className="h-100">
                    <Header />
                    <ContentNavigation />
                        <Switch>
                            <Route exact path='/' component={WelcomeMenu} />
                            <Route path='/principal' component={PrincipleMenu} />
                            <Route path='/mycar' component={MycarMenu} />
                            <Route path='/abc' component={abcMenu} />
                            <Route path='/ijkmenu' component={ijkMenu} />
                            <Route path='/xyzmenu' component={xyzMenu} />
                        </Switch>

                </div>
            </Router>
        );
    }

header.js

render() {
        return (
                   <div className="header-right text-right header-text-pd-tp">
                    <span>
                         <i className ="icon-arrow-left prev-next-icon prev-icon"></i> 
                         BACK 
                   </span>
                    Current Chapter
                        <span> 
                         NEXT
                        <i className="icon-arrow-right prev-next-icon next-icon" aria-hidden="true"></i> 
                       </span>
                    </div>
       )
    }
2

There are 2 answers

2
Vivian On

This is one way to do routing

this.props.history.push({
                pathname: '/your_route_path'
            })
0
akhtarvahid On

Multiple ways- you can navigate to other component.

1-using Link

import {Link} from 'react-router-dom'

<Link to="/ijkmenu"> 
      NEXT
    <i className="icon-arrow-right prev-next-icon next-icon" aria-hidden="true"></i> 
</Link>

2-using this.props.history.push()

<span onClick={()=> this.props.history.push('/ijkmenu')}> 
          NEXT
        <i className="icon-arrow-right prev-next-icon next-icon" aria-hidden="true"></i> 
   </span>