Skip to content
Advertisement

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 www.example.com/signup then the modal would render the content specific to the sign up process, and when the user is on www.example.com/shop 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 www.example.com/shop/294594 (or any other route that stars with /shop) then the modal still displays the same content as for www.example.com/shop.

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!

Advertisement

Answer

You can create a FAQ component like this https://codesandbox.io/s/react-router-tgh8c?file=/components/FAQ.js

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 (
    <React.Fragment>
      <button onClick={() => showModal(!modal)}>FAQ</button>
      <div className="modal">{modal && <div>{component}</div>}</div>
    </React.Fragment>
  );
}

export default FAQ;

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