skip to Main Content

I have Routes branchiing like this below

const App = () => {
    return (
      <BrowserRouter>
        <Routes>
          <Route path={`/`} element={<TopPage />} />
          <Route path={`/dev`} element={<TopPage />} />

Now I want to do some task depending on url like this below.

(This code is wrong, but I hope it can explain what I want to do)

const App = () => {
    return (
      <BrowserRouter>
        <Routes>
          <Route path={`/`} dothis={var variable="prod";render(<TopPage>) />
          <Route path={`/dev`} dothis={var variable="dev";render(<TopPage>)/>

Is there any way to do this?

2

Answers


  1. You should useEffect or useMemo (or you could just write code in your component inline for the useMemo case) depending on your use case.

    let location = useLocation();
    
    const isDev = useMemo(() => {
      return location.pathname.startsWith("/dev");
    }, [location]);
    // could also be just 
    const isDev = location.pathname.startsWith("/dev");
    
    useEffect(() => {
      if (location.pathname.startsWith("/dev") {
        console.log("DEV ENABLED");
      }
    }, [location]);
    
    Login or Signup to reply.
  2. Looks like you’re wanting props

    const App = () => {
        return (
          <BrowserRouter>
            <Routes>
              <Route path={`/`} element={<TopPage environment="prod" />} />
              <Route path={`/dev`} element={<TopPage environment="dev" />} />
    

    Then in your TopPage component

    const TopPage = ({environment}) => {
      // use `environment` here
    }
    

    If you’re using TypeScript, you should look into using an enum or union to prevent making typos in the name or forgetting the possible valid values.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search