Learn
Routing

🌐 Page Routing

As of yet Pre-ReactJS supports a single level of routing through a file-based approach. This means that whenever you create a file in the Pages directory, a corresponding route is automatically generated.

For example, if you create a file named YourPage, you can access its content by navigating to http://localhost:3000/YourPage.

In addition to handling requests from the search bar, Pre-ReactJS provides a dedicated function named after your page (e.g., YourPage) for application-level navigation.

How it Works

Creating a new route is as simple as adding a new file in your Pages/ directory. Once you do that, your server will automatically generate a new route upon restart (or instantly if you're using a dev server).

You can navigate to the new page either by entering the route directly in the search bar or by calling the function named after your file within your application.

Making a navbar

To add navigation to your application, start by locating the Navbar.js component within the components/Navbar/ directory. This component will handle navigation across your app.

Step 1: Create a New Page

Begin by creating a new file in your Pages/ directory: Pages/new_page.js Edit the file as follows:

import Navbar from "../components/Navbar/Navbar.js"
 
let NewPage = /*html*/`
<div class="Text">
    <div id="headAndNav">
        <h1 class="title">Hi There :) </h1>
        <div class="bg">${Navbar()}</div>
    </div>
    <p class="subHead">This a new page you just created</p>
    <p class="paragraph">
        Try fiddling around with the navbar links and try editing the stuff there. 
    </p>
</div>
`
 
export default NewPage

now visit http://localhost:3000/new_page you'll find your new page there. Make sure your server is running in dev mode; if not, restart the server.

Step 2: Add Navigation to the Navbar

After creating the new route, you'll likely want to navigate to it via the navbar. While you could link directly to the page URL, this would cause a full page refresh, which is less efficient. Instead, you can directly call the newly created new_page() function from your navbar.

Edit your components/Navbar/Navbar.js as follows ::

const Navbar = () =>{
  return(
      /*html*/`
  <link rel="stylesheet" href="./components/Navbar/Navbar.css">
  <ul id="navbar">
      <li onclick="Home()">home</li>
      <li onclick="Contact()">contact</li>
      <li onclick="new_page()">new_page</li>
  </ul>
  `)
}
export default Navbar

With this update, you'll see a new entry in your navbar that links directly to new_page. Now you're all set to navigate seamlessly within your application!

Observation

In this chapter you learned how you can acheive Page routing with Pre-ReactJS.