Categories
React Answers

How to get URL path parameters in React Router v4?

Sometimes, we want to get URL path parameters in React Router v4.

In this article, we’ll look at how to get URL path parameters in React Router v4.

How to get URL path parameters in React Router v4?

To get URL path parameters in React Router v4, we can call our component with the withRouter higher order component.

Then we can import that component and use that as the route component.

For instance, we write

import { withRouter } from "react-router";

class BookDetailedView extends React.Component {
  render() {
    const id = this.props.match.params.id;
    //...
  }
}
export default withRouter(BookDetailedView);

to define the BookDetailedView component that gets the id URL parameter from this.props.match.params.id.

This is available because we have withRouter(BookDetailedView) and we export that.

We then import this component and use that in our Router component in the render prop to render it when we navigate to the URL that matches the Route path.

Conclusion

To get URL path parameters in React Router v4, we can call our component with the withRouter higher order component.

Then we can import that component and use that as the route component.

Categories
React Answers

How to access a URL parameter with React Router v6?

Sometimes, we want to access a URL parameter with React Router v6.

In this article, we’ll look at how to access a URL parameter with React Router v6.

How to access a URL parameter with React Router v6?

To access a URL parameter with React Router v6, we can use the useParams hook.

For instance, we write

import React from "react";
import { Button } from "antd";
import { useParams } from "react-router-dom";

const DeleteUser = () => {
  const { id } = useParams();
  const handleDelete = async () => {
    // handle delete function
  };

  return <Button onClick={handleDelete}>Delete User</Button>;
};

export default DeleteUser;

to call useParams to return the value of the id URL parameter.

Then we can use that anywhere else in the DeleteUser component code.

Conclusion

To access a URL parameter with React Router v6, we can use the useParams hook.

Categories
React Answers

How to intercept and handle browser’s back button in React Router?

Sometimes, we want to intercept and handle browser’s back button in React Router.

In this article, we’ll look at how to intercept and handle browser’s back button in React Router.

How to intercept and handle browser’s back button in React Router?

To intercept and handle browser’s back button in React Router, we can listen for changes in the history object with the history.listen method.

For instance, we write

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

const Comp = () => {
  const [locationKeys, setLocationKeys] = useState([]);
  const history = useHistory();

  useEffect(() => {
    return history.listen((location) => {
      if (history.action === "PUSH") {
        setLocationKeys([location.key]);
      }

      if (history.action === "POP") {
        if (locationKeys[1] === location.key) {
          setLocationKeys(([_, ...keys]) => keys);

          // Handle forward event
        } else {
          setLocationKeys((keys) => [location.key, ...keys]);

          // Handle back event
        }
      }
    });
  }, [locationKeys]);

  //...
};

to call the useEffect hook with a callback that calls history.listen to listen for history changes.

If history.push is 'PUSH', then we’re going forward.

If it’s 'POP', then we used the back button.

In either case, we call setLocationKeys to update the locationKeys object.

Conclusion

To intercept and handle browser’s back button in React Router, we can listen for changes in the history object with the history.listen method.

Categories
React Answers

How to match multiple path names for a same component in React Router?

Sometimes, we want to match multiple path names for a same component in React Router

In this article, we’ll look at how to match multiple path names for a same component in React Router.

How to match multiple path names for a same component in React Router?

To match multiple path names for a same component in React Router, we can make changes according to the React Route version we’re using.

If we’re using React Router v4, we set the path prop to an array of paths to match.

For instance, we write

<Router>
  <Route path={["/home", "/users", "/widgets"]} component={Home} />
</Router>

to set the path prop to ["/home", "/users", "/widgets"] to match all of the routes listed.

In React Router v6, we use the useRoutes hook by writing

import React from "react";
import { BrowserRouter as Router, useRoutes } from "react-router-dom";

const App = () =>
  useRoutes([
    { path: "/home", element: <Home /> },
    { path: "/users", element: <Home /> },
    { path: "/widgets", element: <Home /> },
  ]);

const AppWrapper = () => (
  <Router>
    <App />
  </Router>
);

We call useRoutes with an array of route objects and then wrap Router around that to add the routes to our app.

path has the path and element has the component to render given the path.

Conclusion

To match multiple path names for a same component in React Router, we can make changes according to the React Route version we’re using.

Categories
React Answers

How to use anchors with React Router?

Sometimes, we want to use anchors with React Router

In this article, we’ll look at how to use anchors with React Router.

How to use anchors with React Router?

To use anchors with React Router, we can use the react-router-hash-link package.

To install it, we run

npm install react-router-hash-link

Then we use it by writing

import { HashLink as Link } from "react-router-hash-link";

//...

<Link to="home-page#section-three">Section three</Link>;

to add the HashLink component and set its to prop to a URL with the ID of the element to scroll to after the hash.

Conclusion

To use anchors with React Router, we can use the react-router-hash-link package.