Categories
React Answers

How to add an active class to a Link from React Router?

Sometimes, we want to add an active class to a Link from React Router.

In this article, we’ll look at how to add an active class to a Link from React Router.

How to add an active class to a Link from React Router?

To add an active class to a Link from React Router, we can use the NavLink component with the activeClassName prop.

For instance, we write

<NavLink to="/hello" activeClassName="active">
  Hello
</NavLink>

to add a NavLink component with the to prop set to the destination URL.

And the activeClassName set to the CSS class that we apply when we reach the destination URL.

Conclusion

To add an active class to a Link from React Router, we can use the NavLink component with the activeClassName prop.

Categories
React Answers

How to navigate programmatically in React Router v4?

Sometimes, we want to navigate programmatically in React Router v4.

In this article, we’ll look at how to navigate programmatically in React Router v4.

How to navigate programmatically in React Router v4?

To navigate programmatically in React Router v4, we can use the this.props.history.push method.

For instance, we write

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

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: "",
    };
  }

  submit = (event) => {
    event.preventDefault();
    this.props.history.push('/theUrlYouWantToGoTo');
  };

  render() {
    return (
      <form onSubmit={this.submit}>
        <input
          type="text"
          onChange={(event) => this.setState({ input: event.target.value })}
        />

        <button type="submit">Submit</button>
      </form>
    );
  }
}

export default withRouter(Form);

to call this.props.history.push with '/theUrlYouWantToGoTo' to go to /theUrlYouWantToGoTo when the submit method is called.

We call withRouter with Form so that history is injected into the props of Form.

Conclusion

To navigate programmatically in React Router v4, we can use the this.props.history.push method.

Categories
React Answers

How to add multiple parameters with React Router?

Sometimes, we want to add multiple parameters with React Router.

In this article, we’ll look at how to add multiple parameters with React Router.

How to add multiple parameters with React Router?

To add multiple parameters with React Router, we can get the URL parameters from the useParams hook.

For instance, we add

<Route path="/:category/:id" exact component={ItemDetails} />;

to add the category and id parameters to the Route.

Then we can get it from ItemDetails with

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

export default function ItemDetails(props) {
  const { id, category } = useParams();
  return (
    <div>
      {id}
      {category}
    </div>
  );
}

We call useParams to return an object with the id and category parameters.

Conclusion

To add multiple parameters with React Router, we can get the URL parameters from the useParams hook.

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.