Skip to content

How to make a “global” component render content based on url route?

I have a FAQ button that’s fixed onto the bottom right corner of the screen (it’s on every screen of the website), when clicked a modal pops out displaying frequent asked questions and their respective answers, I’d like the modal to display different content based on the url that the user is on.

For example: if the user is on then the modal would render the content specific to the sign up process, and when the user is on only the faq’s related to shopping should appear. This should be taking into account the first part of the url params, so if a user goes to (or any other route that stars with /shop) then the modal still displays the same content as for

Is there any good way to to this with react-router (or any other alternative)? I did some research into react-router useParams hook but I’m not sure if it’s the go-to solution since I’m just a beginner in routing. Thanks for your time!



You can create a FAQ component like this

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

const SignupFaq = () => <p>Sign up questions</p>;
const ShopFaq = () => <p>Shop questions</p>;

const faqs = {
  signup: {
    component: <SignupFaq />
  shop: {
    component: <ShopFaq />

function FAQ() {
  const { pathname } = useLocation();

  const { component } = faqs[pathname.split("/")[1]];

  const [modal, showModal] = React.useState(false);

  return (
      <button onClick={() => showModal(!modal)}>FAQ</button>
      <div className="modal">{modal && <div>{component}</div>}</div>

export default FAQ;

User contributions licensed under: CC BY-SA
6 People found this is helpful