skip to Main Content

I have a modal on my page (Next.js) that is triggered clicking a button:

<button type='button' onClick={() => setOpen(true)}>

The modal:

<Modal
  id='demo'
  show={isOpen}
  onClose={() => setOpen(false)}
>

The modal is hidden by default. And I would like to send a link to client. When the client clicks on the link, they will be brought to the page with the modal opened. Is it possible to do this? How? Thank you very much.

I tried to put the id in the URL like: https://example.com/contact#demo , but no luck. I was thinking about using the query mark(?), but can’t figure how it would work.

2

Answers


  1. if NextJS is with react-dom then you can use useSearchParams from react-router-dom

    import { useSearchParams } from 'react-router-dom'
    ...
    ....
    const MyComponent = () => {
      const [searchParams, setSearchParams] = useSearchParams();
      const q = searchParams.get('demo')
    
      return (
      )
    }
    
    Login or Signup to reply.
  2. you could detect the referrer which tells you from which link the client was navigated to your page. you can define getServerSideProps

    import { GetServerSideProps } from "next";
    
    export const getServerSideProps: GetServerSideProps = async (context) => {
      let referred=false
      //  headers: IncomingHttpHeaders;
      // IncomingHttpHeaders has 'referer'?: string;
      const referrer=context.req.headers.referer
      if (referrer===YOURlINK){
           referred=true
      }
      return { props: {referred:referred} };
    };
    

    then based on referred prop

    const referred=props.referred
    <Modal
      id='demo'
      // if referred is true, it will show if referred is false, it will look isOpen value
      show={referred || isOpen}
      onClose={() => setOpen(false)}
    >
    

    You could handle this in client side as well

    const [referred,setReferred]=useState(false)
    
    useEffect(() => {
        const referrer = document.referrer;
        if (referrer !== null) {
          console.log(`I was redirected from ${referrer}`);
        }
       if (referrer===YOURlINK){
           setReferred(true)
       }
      }, []);
    

    using referred state value

    <Modal
      id='demo'
      show={referred || isOpen}
      onClose={() => setOpen(false)}
    >
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search