Wasyster
Wasyster

Reputation: 2535

React router v4 dynamic parameter

I need a dynamic routing in my Reac app that use reac-router v4. I want the following adress to build

http://localhost:7777/oceanside-yaht-club/booking/search

where oceanside-yaht-club can dynamicly change, depending on our customer.

But this is what I get now whit my try:

http://localhost:7777/oceanside-yaht-club/:pathParam/booking/search

Here is how I tried:

export enum Routes
{
    Home = '',
    BookingSearch = 'booking/search',
    BookingOffers = 'booking/offers',
    BookingExtras = 'booking/extras',
    BookingContactDetails = 'booking/contact',
    BookingBoatDetails = 'booking/boat',
    BookingPayment = 'booking/payment',
    BookingComplete = 'booking/complete',
    BookingClose = 'booking/close'
}

export module Urls
{
    export const home = `/${Routes.Home + ':pathParam?'}`;
    export const bookingSearch = ':pathParam' + `/${Routes.BookingSearch}`;
    export const bookingOffers = `/${Routes.BookingOffers}`;
    export const bookingExtras = `/${Routes.BookingExtras}`;
    export const bookingContactDetails = `/${Routes.BookingContactDetails}`;
    export const bookingBoatDetaisl = `/${Routes.BookingBoatDetails}`;
    export const bookingPayment = `/${Routes.BookingPayment}`;
    export const bookingComplete = `/${Routes.BookingComplete}`;
    export const bookingClose = `/${Routes.BookingClose}`;
}

export const IndexRoutes = () =>
    <React.Fragment>
        <Route exact path={ Urls.home } component={ App } />
        <Route exact path={ Urls.bookingSearch } component={ Search } />
        <Route exact path={ Urls.bookingOffers } component={ Offers } />
        <Route exact path={ Urls.bookingExtras } component={ Extras } />
        <Route exact path={ Urls.bookingContactDetails } component={ ContactDetails } />
        <Route exact path={ Urls.bookingBoatDetaisl } component={ BoatDetails } />
        <Route exact path={ Urls.bookingPayment } component={ Payment } />
        <Route exact path={ Urls.bookingComplete } component={ Complete } />
        <Route exact path={ Urls.bookingClose } component={ WindowsCloseDialog } />
    </React.Fragment>

and this is how I push in the router history

const url: string = `${this.store.state.marinaData.MarinaUrlName}/${Urls.bookingSearch}`;
// const url: string = `oceanside-yaht-club/${Urls.bookingSearch}`; //for test
this.props.history.push(url);

I even tried this regex, but not figured out how to implement in my code

thnx

Upvotes: 0

Views: 64

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281736

You cannot use the Route path param as it is directly while passing url to history.push, instead it needs a complete link.

You can change the code to

const url: string = `${this.store.state.marinaData.MarinaUrlName}/${Routes.BookingSearch}`;

this.props.history.push(url);

Upvotes: 1

Related Questions