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.

Categories
React Answers

How to use normal anchor links with React Router?

Sometimes, we want to use normal anchor links with React Router.

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

How to use normal anchor links with React Router?

To use normal anchor links with React Router, we can use the Link component.

For instance, we write

import React from "react";
import { Link } from "react-router-dom";

const Comp = () => {
  //...
  return (
    <Link to={{ pathname: "/this-view-path", hash: "#faq-1" }}>Question 1</Link>
  );
};

to render the Link component by setting the to prop to the destination we want to go when the link is clicked.

Link renders into an anchor element.

Conclusion

To use normal anchor links with React Router, we can use the Link component.