score:0

Accepted answer

in my opinion it's not a problem to have your "enter verification code" page be accessible from the url. but if you want to do this then yes it can be done.

the render component for your verification page needs to check some condition. if that condition is met then it loads the page. if not, it renders a <redirect/> to your form page.

i am using a property in location.state as that condition. when you navigate within the app then you will pass this property in you <link/> component by using a to object instead of just a path string.

<link to={{ pathname: "/verify", state: { fromapp: true } }}>verify</link>

the component for the verification page will use the uselocation hook to access the current location and see if the location state includes the fromapp property which we set.

const location = uselocation();

if (!location.state?.fromapp) {
    return <redirect to="/" />;
}

i created a very simple codesandbox demo.

you get redirected if you go to "/verify" directly. but you can access it just fine by clicking on the "verify" link from the home page.

complete code:

import {
  browserrouter,
  link,
  redirect,
  route,
  switch,
  uselocation
} from "react-router-dom";

const home = () => (
  <div>
    <h1>home</h1>
    <link to={{ pathname: "/verify", state: { fromapp: true } }}>verify</link>
  </div>
);

const verificationpage = () => {
  const { state } = uselocation();

  if (!state?.fromapp) {
    return <redirect to="/" />;
  }

  return (
    <div>
      <h1>enter verification code</h1>
      <input />
      <button>submit</button>
    </div>
  );
};

export default function app() {
  return (
    <browserrouter>
      <switch>
        <route path="/verify" component={verificationpage} />
        <route path="/" component={home} />
      </switch>
    </browserrouter>
  );
}

Related Query

More Query from same tag