Conteúdo do curso
Immersion in React: Comprehensive Course for Beginners
Sobre a Aula

Implementing Page Navigation

In the previous topic, we learned about data entry validation in forms.

Today, we’ll learn about how to implement page navigation in React using React Router.

What is React Router?

React Router is a library that makes it easy to implement page navigation in React applications.

With React Router, we can:

  • Create links to navigate between different pages.
  • Define routes for different pages.
  • Control the navigation flow in the application.

How to Use React Router?

To use React Router, we need to follow these steps:

  • Install React Router:
npm install react-router-dom
  • Import React Router:
import { BrowserRouter, Route, Link } from "react-router-dom";
  • Create a BrowserRouter component:
const App = () => {
  return (
    <BrowserRouter>
      <div>
        <Header />
        <Main />
        <Footer />
      </div>
    </BrowserRouter>
  );
};
  • Create routes for different pages:
const App = () => {
  return (
    <BrowserRouter>
      <div>
        <Header />
        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
        <Footer />
      </div>
    </BrowserRouter>
  );
};
  • Create links to navigate between different pages:
const Home = () => {
  return (
    <div>
      <h1>Home Page</h1>
      <Link to="/about">About</Link>
    </div>
  );
};

const About = () => {
  return (
    <div>
      <h1>About Page</h1>
      <Link to="/">Home</Link>
    </div>
  );
};

Example of Page Navigation

Let’s see an example of how to implement page navigation using React Router:

const App = () => {
  return (
    <BrowserRouter>
      <div>
        <Header />
        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
        <Footer />
      </div>
    </BrowserRouter>
  );
};

const Home = () => {
  return (
    <div>
      <h1>Home Page</h1>
      <Link to="/about">About</Link>
    </div>
  );
};

const About = () => {
  return (
    <div>
      <h1>About Page</h1>
      <Link to="/">Home</Link>
    </div>
  );
};

In this example, the App component uses the BrowserRouter component to create a navigation context. The App component defines two routes: one for the home page (/) and another for the about page (/about). The Home component uses the Link component to create a link to the about page. The About component uses the Link component to create a link to the home page.

Important Notes

When implementing page navigation, it’s important to:

  • Use descriptive route names: Route names should be descriptive so that the user understands which page they are navigating to.
  • Use meaningful links: Links should have a clear meaning for the user.
  • Handle navigation errors: It’s important to handle navigation errors, such as trying to access a page that doesn’t exist.
Entrar na conversa
Rolar para cima