Home > Software engineering >  How to check for a randomly generated url that begins with a phrase with Route hook in reactjs
How to check for a randomly generated url that begins with a phrase with Route hook in reactjs

Time:10-22

I am trying to setup a website where you can register people and it will add their information to a database. You can then search for these people's names on the main page and it will filter results depending on name. Each name that pops up that is similar to the searched string will be a Link hook from reactjs and it will take you to a page with the pathname of:

"/student_info_" element

And on this page will have the person's information. I am having trouble rendering the page on the App.js as it generates partially random url and the code I have in my App.js is :

return (

    <div>
      <Switch>
        <Route path="/" exact>
          <MainPage />
        </Route>
        <Route path="/register_student">
          <RegisterPage />
        </Route>
        <Route path="/student_info_">
          <StudentInfo />
        </Route>
      </Switch>
    </div>

  );

This doesn't seem to work for whatever reason. I test this as in the student info page I include:


    return (

        <div className="btn-textfield">

            {pathName}
            
        </div>

    );

And when I am on the student info page it does not show any information. I am fairly certain the issue is in the App.js checking the pathname of the url and displaying the correct page, but I am not sure exactly how to fix it. I appreciate any responses.

CodePudding user response:

I believe you are looking for route parameters.

In App.js you could do:

<Route path="/student_info/:id">
  <StudentInfo />
</Route>

Then inside the StudentInfo component you could get the :id part of the current route like this:

import { useParams } from "react-router-dom";

 ...

const { id } = useParams();

return (
  <div className="btn-textfield">
    {id}
  </div>
);

If you want the paths to look exactly like /student_info_%ID%, you can also achieve it using the same approach & treating this whole part of the path as an :id.

  • Related