jcmujica
jcmujica

Reputation: 91

Contitional url with react router v5

I'm trying to add a 'company/:companyId' base route to my react app using react-router v5.

I dont want my /login /register routes to use this base url, I only want to force a logged in user to navigate using the base url.

I've tried using somethign among the lines of:

<BrowserRouter baseurl={companyId ? `/company/${comapnyId}` : ''} >

But Ive gotten /company/undefined upon logging in or the router to comeptetly ignore the base url is all attempts.

Upvotes: 1

Views: 478

Answers (1)

triedthatalready
triedthatalready

Reputation: 11

Here you can create your condition to include a company id, or some other factor like isLogged in. I have done this with checking if a user is on a mobile device. If they are my condition will return them to a mobile landing page.

const PrivateRoute = ({ component: Component, condition }) => {
  return (
    <Route
      {...rest}
      render={(props) =>
        condition? <Component {...props} /> : <Redirect to={condition ? '/condition-page' : '/somewhere-else'} />
      }
    />
  );
};
import { BrowserRouter as Router, Route, Redirect } from "react-router-dom";

    <Router history={history}>
    <PrivateRoute exact path="/" condition={true} component={Page1} />
    <Route exact path="/page2" component={Page2} />
    <Route exact path="/page3" component={Page3} />
  </Router>

if youre trying to nest routes you can do them inside the route itself.

    <Router history={history}>
    <Route exact path="/companies" component={Companies} />
  </Router>

// inside companies component you nest a route
    <Route exact path="/companies/:id" component={Company} />

Upvotes: 1

Related Questions