Just Learn Code

Navigating with React Router: Declarative vs Programmatic Approach

Declarative vs.

Programmatic Navigation in React Router DOM

React Router is a popular library used in React applications to implement navigation functionality.

It allows developers to create dynamic client-side routing, allowing users to navigate through different sections of the application without having to reload the page. React Router provides two different ways to navigate through different routes within the application – declarative navigation and programmatic navigation.

In this article, we will explore both approaches and the benefits they offer.

Declarative Navigation with Link Component

Declarative navigation is the recommended approach in React Router. It involves using the component which allows us to create links to different routes within the application with a simple syntax.

Let’s take a look at an example:

“`

import { Link } from “react-router-dom”;

function NavigationBar() {

return (

);

}

export default NavigationBar;

“`

Here, we are using the component to create links to different pages within the application. When a user clicks on a link, React Router automatically updates the browser URL and renders the appropriate component.

The component takes a “to” prop, which specifies the route to navigate to. When the user clicks the link, the browser’s history is automatically updated, and the corresponding component is rendered.

Using declarative navigation ensures that the application remains in sync with the browser’s history. This means that users can use the browser’s back and forward buttons to navigate between pages.

Programmatic Navigation with history Object

Programmatic navigation is an alternative to declarative navigation. It involves using the history object to manipulate the browser’s history and change the current URL.

The history object is provided by React Router and can be accessed using the “useHistory” hook in functional components or the “history” prop in class components. The history object provides several methods that can be used for programmatic navigation –

push(),

pop(), and

replace().

Let’s take a look at them in detail.

push()

The

push() method is used to push a new entry onto the browser’s history stack. This allows us to navigate to a new URL programmatically.

Here is an example:

“`

import { useHistory } from “react-router-dom”;

function navigateToBlogPost(id) {

const history = useHistory();

history.push(`/blog/${id}`)

}

“`

In the example above, we are using the useHistory hook to access the history object, and the

push() method to navigate to a specific blog post based on its ID.

pop()

The

pop() method is used to pop the current entry from the browser’s history stack. This allows us to go back to the previous page in the history.

Here is an example:

“`

import { useHistory } from “react-router-dom”;

function goBack() {

const history = useHistory();

history. pop();

}

“`

In the example above, we are using the useHistory hook to access the history object, and the

pop() method to go back to the previous page in the history.

replace()

The

replace() method is used to replace the current entry on the browser’s history stack with a new entry. This allows us to navigate to a new URL programmatically but without adding a new entry to the history.

Here is an example:

“`

import { useHistory } from “react-router-dom”;

function redirectToHomepage() {

const history = useHistory();

history.replace(“/”);

}

“`

In the example above, we are using the useHistory hook to access the history object, and the

replace() method to navigate to the homepage without adding a new entry to the history.

Accessing history Object

To access the history object, we can use the “useHistory” hook in functional components or the “history” prop in class components. Here is an example of using the “useHistory” hook:

“`

import { useHistory } from “react-router-dom”;

function BlogPost(props) {

const history = useHistory();

function goBack() {

history.goBack();

}

return (

{props.title}

{props.content}

);

}

export default BlogPost;

“`

In the example above, we are using the useHistory hook to access the history object, and the goBack() function to go back to the previous page in the history when the “Go Back” button is clicked.

Here is an example of using the “history” prop in class components:

“`

import React, { Component } from “react”;

class BlogPost extends Component {

constructor(props) {

super(props);

this.state = {

post: null,

};

}

componentDidMount() {

// Fetch blog post from API

const postId = this.props.match.params.id;

fetch(`/api/posts/${postId}`)

.then((response) => {

return response.json();

})

.then((data) => {

this.setState({

post: data,

});

});

}

navigateToBlogList() {

this.props.history.push(“/blog”);

}

render() {

const { post } = this.state;

return (

{post && (

{post.title}

{post.content}

)}

);

}

}

export default BlogPost;

“`

In the example above, we are using the “history” prop to navigate back to the blog list when the “Back to Blog List” button is clicked.

Programmatic Navigation in React Router 4.0.0+

React Router 4.0.0 introduced a new way to use programmatic navigation using the useHistory() hook in functional components and the history prop in class components. Here is an example of using the useHistory() hook in a functional component:

“`

import { useHistory } from “react-router-dom”;

function Home() {

const history = useHistory();

function navigateToBlog() {

history.push(“/blog”);

}

return (

Welcome to my Blog!

);

}

export default Home;

“`

In the example above, we are using the useHistory() hook to access the history object, and the

push() method to navigate to the blog page when the “Go to Blog” button is clicked.

Here is an example of using the history prop in a class component:

“`

import React, { Component } from “react”;

class Blog extends Component {

navigateToBlogPost(id) {

this.props.history.push(`/blog/${id}`);

}

render() {

return (

Blog Posts

  • this.navigateToBlogPost(1)}>Post 1
  • this.navigateToBlogPost(2)}>Post 2
  • this.navigateToBlogPost(3)}>Post 3

);

}

}

export default Blog;

“`

In the example above, we are using the history prop to navigate to specific blog posts when a post is clicked.

Programmatic Navigation in React Router 5.1.0+

React Router 5.1.0 introduced a new way to use programmatic navigation in functional components using a custom component and a historyReference. Here is an example:

“`

import { Route, useHistory } from “react-router-dom”;

function Blog() {

const history = useHistory();

function navigateToBlogPost(id) {

history.push(`/blog/${id}`);

}

return (

Blog Posts

  • navigateToBlogPost(1)}>Post 1
  • navigateToBlogPost(2)}>Post 2
  • navigateToBlogPost(3)}>Post 3

path=”/blog/:id”

component={BlogPost}

historyRef={history}

/>

);

}

export default Blog;

“`

In the example above, we are using the Route component to render the BlogPost component when a blog post is clicked.

We are also passing the history object as a prop to the BlogPost component using the historyRef prop.

Programmatic Navigation in React Router 6.0.0+

React Router 6.0.0 introduced a new hook called useNavigate(), which replaces the useHistory() hook used in previous versions. The useNavigate() hook can be used in functional components to navigate programmatically.

Here is an example:

“`

import { useNavigate } from “react-router-dom”;

function Blog() {

const navigate = useNavigate();

function navigateToBlogPost(id) {

navigate(`/blog/${id}`);

}

return (

Blog Posts

  • navigateToBlogPost(1)}>Post 1
  • navigateToBlogPost(2)}>Post 2
  • navigateToBlogPost(3)}>Post 3

);

}

export default Blog;

“`

In the example above, we are using the useNavigate() hook to access the navigate() method, which allows us to navigate programmatically to different pages in the application.

Conclusion

In this article, we have explored declarative and programmatic navigation in React Router. Declarative navigation is the recommended approach and involves using the component to create links to different routes within the application.

Programmatic navigation involves using the history object to manipulate the browser’s history and change the current URL. We have also looked at how to access the history object using the useHistory() hook in functional components and the history prop in class components.

We have also explored programmatic navigation in React Router 4.0.0+, React Router 5.1.0+, and React Router 6.0.0+. Using programmatic navigation can be useful in situations where we need to navigate programmatically, for example, when handling form submissions or displaying data from an external API.

By understanding both declarative and programmatic navigation, we can create more flexible and dynamic applications. React is a popular JavaScript library used for building user interfaces.

One of its key features is the ability to create dynamic client-side routing using a library called React Router. React Router allows developers to implement navigation functionality in their applications, allowing users to move between different sections of the application without having to reload the page.

In React Router, there are two approaches to navigation – programmatic and declarative. Let’s dive into the details of each.

Declarative Navigation

Declarative navigation is the recommended approach in React Router, as it is simpler and more expressive. In declarative navigation, we use the component to create links to different sections of the application.

With this approach, when a user clicks on a link, React Router automatically updates the browser URL and renders the appropriate component. Here’s an example of using declarative navigation in React Router:

“`

import { Link } from ‘react-router-dom’;

function Navigation() {

return (

);

}

“`

With the component, we can easily create links to different sections of the application by specifying the ‘to’ prop.

This approach is easy to use and very expressive.

Programmatic Navigation

Programmatic navigation in React Router involves manipulating the browser’s history object to programmatically navigate through the application. The history object can be accessed using the useHistory() hook in functional components or the history prop in class components.

Here’s an example of using programmatic navigation in React Router:

“`

import { useHistory } from ‘react-router-dom’;

function Login(props) {

const history = useHistory();

function handleLogin() {

// Login user and redirect to dashboard

history.push(‘/dashboard’);

}

return (

{/* Login form */}

);

}

“`

In this example, we use the useHistory() hook to access the history object and the

push() method to navigate to the dashboard page when the user logs in.

Accessing the History Object

To use programmatic navigation, we need to access the history object. In functional components, we use the useHistory() hook, while in class components, we use the history prop.

Here’s an example of accessing the history object using the useHistory() hook:

“`

import { useHistory } from ‘react-router-dom’;

function Home(props) {

const history = useHistory();

function handleLogout() {

// Logout user and navigate to login

props.logout();

history.push(‘/login’);

}

return (

Welcome Home!

);

}

“`

Here’s an example of accessing the history object using the history prop:

“`

import React, { Component } from ‘react’;

class Dashboard extends Component {

handleLogout = () => {

// Logout user and navigate to login

this.props.logout();

this.props.history.push(‘/login’);

};

render() {

return (

Dashboard

);

}

}

export default Dashboard;

“`

In class components, the history prop is passed in as a prop by React Router. Using

Programmatic Navigation in React Router 4.0.0+

React Router 4.0.0 introduced a new way to use programmatic navigation using the useHistory() hook in functional components and the history prop in class components.

Here’s an example of using programmatic navigation in React Router 4.0.0+:

“`

import { useHistory } from ‘react-router-dom’;

function HomePage() {

const history = useHistory();

function handleClick() {

history.push(‘/about’);

}

return (

Welcome to my website!

);

}

“`

In this example, we use the useHistory() hook to access the history object and the

push() method to navigate to the about page when the button is clicked. Using

Programmatic Navigation in React Router 5.1.0+

React Router 5.1.0 introduced a new way to use programmatic navigation in functional components using a custom component and a historyReference.

Here’s an example of using programmatic navigation in React Router 5.1.0+:

“`

import { Route, useHistory } from ‘react-router-dom’;

function HomePage() {

const history = useHistory();

function handleClick() {

history.push(‘/about’);

}

return (

Welcome to my website!

);

}

“`

In this example, we use a custom component with the historyReference prop to navigate to the about page when the button is clicked. Using

Programmatic Navigation in React Router 6.0.0+

React Router 6.0.0 introduced a new hook called useNavigate(), which replaces the useHistory() hook used in previous versions.

The useNavigate() hook can be used in functional components to navigate programmatically. Here’s an example of using programmatic navigation in React Router 6.0.0+:

“`

import { useNavigate } from ‘react-router-dom’;

function LoginPage() {

const navigate = useNavigate();

function handleLogin() {

// Login user and navigate to dashboard

navigate(‘/dashboard’);

}

return (

{/* Login form */}

);

}

“`

In this example, we use the useNavigate() hook to access the navigate() method and navigate to the dashboard when the user logs in.

Conclusion

In conclusion, React Router provides two approaches to navigation – programmatic and declarative. Declarative navigation is the simpler and more expressive approach, whereas programmatic navigation involves manipulating the browser’s history object to programmatically

Popular Posts