Categories
React Answers

How to use React Router with a layout page or multiple components per page?

Sometimes, we want to use React Router with a layout page or multiple components per page.

In this article, we’ll look at how to use React Router with a layout page or multiple components per page.

How to use React Router with a layout page or multiple components per page?

To use React Router with a layout page or multiple components per page, we can create an array with the routes and layout component value for each route.

And then we can render the array into routes.

For instance, we write

const routes = [
  {
    layout: Layout1,
    subRoutes: [
      {
        path: "/route1/:id/:token",
        component: SetPassword,
      },
      {
        exact: true,
        path: "/",
        component: SignIn,
      },
    ],
  },
  {
    layout: Layout2,
    subRoutes: [
      {
        path: "/route2",
        component: Home,
      },
    ],
  },
];

const App = () => {
  //...
  return (
    <Switch>
      {routes.map((route, i) => (
        <Route
          key={i}
          exact={route.subRoutes.some((r) => r.exact)}
          path={route.subRoutes.map((r) => r.path)}
        >
          <route.layout>
            {route.subRoutes.map((subRoute, i) => (
              <Route key={i} {...subRoute} />
            ))}
          </route.layout>
        </Route>
      ))}
    </Switch>
  );
};

to define the routes array with the layout and subRoutes properties in each object entry.

Then in App, we call routes.map to render each route by calling map with a callback that returns an Router component wrapped around a route.layout component.

And then we render the route.subRoutes items into Routes by calling route.subRoutes.map with a callback to return the Route.

If route.layout renders the children prop then the components inside it should show.

Conclusion

To use React Router with a layout page or multiple components per page, we can create an array with the routes and layout component value for each route.

And then we can render the array into routes.

Categories
React Answers

How to use useParams() inside class component with react-router-dom?

Sometimes, we want to use useParams() inside class component with react-router-dom.

In this article, we’ll look at how to use useParams() inside class component with react-router-dom.

How to use useParams() inside class component with react-router-dom?

To use useParams() inside class component with react-router-dom, we can use the withRouter higher order component.

For instance, we write

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

class TaskDetail extends React.Component {
  componentDidMount() {
    const { id } = this.props.match.params;
    this.fetchData(id);
  }

  fetchData = (id) => {
    // ...
  };

  render() {
    return <div>Yo</div>;
  }
}

export default withRouter(TaskDetail);

to call withRouter with TaskDetail and export the component returned by withRouter.

As a result, in TaskDetail, we can get the route parameters from this.props.match.params.

Conclusion

To use useParams() inside class component with react-router-dom, we can use the withRouter higher order component.

Categories
React Answers

How to force a React Router to load a page, even if we’re already on that page?

Sometimes, we want to force a React Router to load a page, even if we’re already on that page.

In this article, we’ll look at how to force a React Router to load a page, even if we’re already on that page.

How to force a React Router to load a page, even if we’re already on that page?

To force a React Router to load a page, even if we’re already on that page, we can add the forceRefresh prop to the BrowserRouter component.

For instance, we write

<BrowserRouter forceRefresh>...</BrowserRouter>;

to add the forceRefresh prop to BrowserRouter.

Conclusion

To force a React Router to load a page, even if we’re already on that page, we can add the forceRefresh prop to the BrowserRouter component.

Categories
React Answers

How to hide navbar in login page in React Router?

Sometimes, we want to hide navbar in login page in React Router.

In this article, we’ll look at how to hide navbar in login page in React Router.

How to hide navbar in login page in React Router?

To hide navbar in login page in React Router, we can put our nav bar inside the container with the authenticated routes.

For instance, we write

import React from "react";

const MyComponent = () => {
  //...
  return (
    <div className="App">
      <Router>
        <Switch>
          <Route exact path="/" component={Login} />
          <div>
            <NavBar />

            <Route exact path="/addproduct" component={Addproduct}></Route>
            <Route exact path="/products" component={Products}></Route>
          </div>
        </Switch>
      </Router>
    </div>
  );
};

to put NavBar at the same level as the 2 Routes that needs authentication.

NavBar is one level deeper than the Route that renders the Login component, so NavBar won’t be rendered with Login.

Conclusion

To hide navbar in login page in React Router, we can put our nav bar inside the container with the authenticated routes.

Categories
React Answers

How to programmatically update query parameters in React Router?

Sometimes, we want to programmatically update query parameters in React Router.

in this article, we’ll look at how to programmatically update query parameters in React Router.

How to programmatically update query parameters in React Router?

To programmatically update query parameters in React Router, we cal call the history.replace method.

For instance, we write

import React from "react";
import { useHistory, useLocation } from "react-router";

const MyComponent = () => {
  const history = useHistory();
  const location = useLocation();

  const onChange = (event) => {
    const { name, value } = event?.target;
    const params = new URLSearchParams({ [name]: value });
    history.replace({ pathname: location.pathname, search: params.toString() });
  };

  return <input name="search" onChange={onChange} />;
};

to call history.replace in the onChange function to navigate after we change the input value.

We create the query string with the URLSearchParams constructor by calling it with an object with the query string key name and value value.

Then we call history.replace with an object with the search property set to the query string we created with params.toString to navigate with the query string.

Conclusion

To programmatically update query parameters in React Router, we cal call the history.replace method.