Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router nesting to show different components

In my App.js I have the following path:

<Route path="/register" component={RegistrationScreen} />

The registration screen component is:

import React, { Component } from 'react'
import { Route, Switch } from 'react-router';
import RegistrationChooser from './RegistrationChooser';
import BookLoverRegistration from './BookLoverRegistration';
import BookLoverProRegistration from './BookLoverProRegistration';
import PublisherRegistration from './PublisherRegistration';
import LiteraryAgentRegistration from './LiteraryAgentRegistration';

export default class RegistrationScreen extends Component {

    render() {
        return <div>
            <Switch>
                <Route path="/" component={RegistrationChooser} />
                <Route path="/bookLover" component={BookLoverRegistration} />
                <Route path="/bookLoverPro" component={BookLoverProRegistration} />
                <Route path="/publisher" component={PublisherRegistration} />
                <Route path="/literaryAgent" component={LiteraryAgentRegistration} />
            </Switch>
        </div>
    }

}

What i want to achieve is the following:

When visiting /register the RegistrationChooser component is loaded, and when visiting /register/bookLover the BookLoverRegistration component is shown and the RegistrationChooser component is hidden(not showing anymore).

How can I achieve this?

like image 544
randomname Avatar asked Oct 28 '22 21:10

randomname


1 Answers

You need to use the match.path property **RegistrationScreen ** component like this

       <Route path=path={`${props.match.path}/`} component=
             {RegistrationChooser} 
                                                          />

Now change every path to use the match.path property before the path you wrote look at the first route and change ever route using the same pattern you can find more in this link

React Router Api match

export default class RegistrationScreen extends Component {

constructor(props){
      super(props) ;
  }     
render() {
    return <div>
        <Switch>
             <Route path={`${props.match.path}/`} component={RegistrationChooser} />
             <Route path={`${props.match.path}/bookLover`} component=
              {BookLoverRegistration} />
             <Route path={`${props.match.path}/bookLoverPro`} component=
              {BookLoverProRegistration} />
              <Route path="/publisher" component={PublisherRegistration} />
              <Route path="/literaryAgent" component=
               {LiteraryAgentRegistration} 
           />
              </Switch>
           </div>
               }

           }
like image 71
mostafa tourad Avatar answered Nov 08 '22 10:11

mostafa tourad