Categories
React Answers

How to detect previous path in React Router?

Sometimes, we want to detect previous path in React Router.

In this article, we’ll look at how to detect previous path in React Router.

How to detect previous path in React Router?

To detect previous path in React Router, we can set the state property to an object with the location.pathname as the value.

For instance, we write

<Link to={{ pathname: "/nextpath", state: { prevPath: location.pathname } }}>
  Example Link
</Link>;

to set the to prop of the Link component to an object with the state property set to { prevPath: location.pathname }.

location.pathname has the value of the current path, which will become the previous path when we go to /nextpath.

Then we can get the value of prevPath from this.props.location.state if we go to the component that renders /nextPath.

Conclusion

To detect previous path in React Router, we can set the state property to an object with the location.pathname as the value.

Categories
React Answers

How to test components using React Router hooks with Jest?

Sometimes, we want to test components using React Router hooks with Jest.

In this article, we’ll look at how to test components using React Router hooks with Jest.

How to test components using React Router hooks with Jest?

To test components using React Router hooks with Jest, we can mock individual hooks in the react-router-dom module with jest.mock.

For instance, we write

jest.mock("react-router-dom", () => ({
  ...jest.requireActual("react-router-dom"),
  useParams: () => ({
    companyId: "company-id1",
    teamId: "team-id1",
  }),
  useRouteMatch: () => ({ url: "/company/company-id1/team/team-id1" }),
}));

to call jest.mock to mock the react-router-dom module.

We call jest.requireActual to put the actual module in the object we return in the mock callback.

And then override the hooks’ values with the mocked ones.

We set useParams to a function that returns the values we want in the component being tested.

And we do the same with useRouteMatch.

Conclusion

To test components using React Router hooks with Jest, we can mock individual hooks in the react-router-dom module with jest.mock.

Categories
React Answers

How to use useNavigate passing value to another component with react-router-dom v6?

Sometimes, we want to use useNavigate passing value to another component with react-router-dom v6.

In this article, we’ll look at how to use useNavigate passing value to another component with react-router-dom v6.

How to use useNavigate passing value to another component with react-router-dom v6?

To use useNavigate passing value to another component with react-router-dom v6, we can call navigate with an object as the 2nd argument.

For instance, we write

import { Link, useNavigate } from "react-router-dom";

const ComponentA = (props) => {
  const navigate = useNavigate();

  const toComponentB = () => {
    navigate("/componentB", { state: { id: 1, name: "sabaoon" } });
  };

  return (
    <>
      <div>
        <a onClick={() => toComponentB()}>Component B</a>
      </div>
    </>
  );
};

export default ComponentA;

to call navigate with the "/componentB" URL path and an object that we want to pass to the component that renders when we go to /componentB.

Then in ComponentB, which is rendered when we go to /componentB, we get the values from the useLocation hook by writing

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

const ComponentB = () => {
  const location = useLocation();

  return (
    <>
      <div>{location.state.name}</div>
    </>
  );
};

export default ComponentB;

We call the useLocation hook to return the object that we passed in as the 2nd argument of navigate in ComponentA.

And then we get the properties from the location object.

Conclusion

To use useNavigate passing value to another component with react-router-dom v6, we can call navigate with an object as the 2nd argument.

Categories
React Answers

How to fix the “Cannot read property ‘push’ of undefined” error with React Router?

Sometimes, we want to fix the "Cannot read property ‘push’ of undefined" error with React Router.

In this article, we’ll look at how to fix the "Cannot read property ‘push’ of undefined" error with React Router.

How to fix the "Cannot read property ‘push’ of undefined" error with React Router?

To fix the "Cannot read property ‘push’ of undefined" error with React Router, we should call the withRouter component with our route component so the history object is available in the props.

For instance, we write

import { withRouter } from "react-router";

class App extends Component {
  push = () => {
    this.props.history.push("/foo");
  };
  //...
}

export default withRouter(App);

to call withRouter with App so that App has this.props.history.push set.

Now we call this.props.history.push with '/foo' to go to /foo.

Conclusion

To fix the "Cannot read property ‘push’ of undefined" error with React Router, we should call the withRouter component with our route component so the history object is available in the props.

Categories
React Answers

How to create dynamic routes in Gatsby?

Sometimes, we want to create dynamic routes in Gatsby.

In this article, we’ll look at how to create dynamic routes in Gatsby.

How to create dynamic routes in Gatsby?

To create dynamic routes in Gatsby, we modify the gatsby-node.js file to add routing dynamically.

For instance, we write

gatsbty-node.js

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions;

  if (page.path.match(/^\/app/)) {
    page.matchPath = "/app/*";

    createPage(page);
  }
};

to check if page.path matches the /^\/app/ with match.

If it does, we set matchPath to the pattern string to matches on client side.

And then we call createPage with page to update the page.

Then in app.js, we write

import { Router } from "@reach/router";

const SomeSubPage = (props) => {
  return <div>Hi from SubPage with id: {props.id}</div>;
};

const App = () => (
  <Layout>
    <Link to="/app/1">First item</Link>
    <Link to="/app/2">Second item</Link>

    <Router>
      <SomeSubPage path="/app/:id" />
    </Router>
  </Layout>
);

export default App;

to add our routes within Router.

Conclusion

To create dynamic routes in Gatsby, we modify the gatsby-node.js file to add routing dynamically.