简体   繁体   中英

how to do dynamic routing in child component in reactjs?

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

This is one way to do routing

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM