Getting url params in Gatsby

Viewed 1657

I recently started learning React and Gatsby. my page has some URL parameters, how can I get it and put in href attr? Everything works on my local machine. But after gatsby build my variable url = undefined always.

import React from 'react';

const url = typeof window !== `undefined` ? window.location.search : ``;

const Article = ({
  content: {
    text,
    limit,
    rate,
    term,
    link,
    logo: {
      title,
      file: {
        URL,
      },
    },
  },
}) => {

  return (
    <Articles>
      <div>
        <button className="btn">
          <a href={url} target="_blank" rel="noreferrer" id="link-mfo">
            Получить деньги
          </a>
        </button>
      </div>
    </Articles>
  );
};
1 Answers

You need to use a useState to store that data and make them available in every change to your href attribute. Something like this should do the trick:

import React, { useEffect, useState } from 'react';
    
const Article = ({
  content: {
    text,
    limit,
    rate,
    term,
    link,
    logo: {
      title,
      file: {
        URL,
      },
    },
  },
}) => {
  const [urlParams, setUrlParams] = useState(``);
  useEffect(() => {
    if(typeof window !==`undefined`){
      const queryString = window.location.search;
      const urlParams = new URLSearchParams(queryString);
      if(urlParams){
        setUrlParams(urlParams);
      }
    }
  }, []);

  return (
    <Articles>
      <div>
        <button className="btn">
          <a href={urlParams} target="_blank" rel="noreferrer" id="link-mfo">
            Получить деньги
          </a>
        </button>
      </div>
    </Articles>
  );
};

This is basically a classic combination of useState and useEffect hooks. Once the DOM tree is loaded (empty deps, []) the function to get the URL parameters is triggered and stores the result in setUrlParams. Finally, you are passing the value in the href attribute by href={urlParams}. Of course, you can find other workarounds.

Your statement:

const url = typeof window !== `undefined` ? window.location.search : ``;

Set as a const, it was fixing the value in the SSR (Server-Side Rendering), because is where gatsby build occurs, to undefined and was never updated.

Related