5

There is a small component in which, when you click on the button, the search param changes in the url. But when search param changes, the entire component is re-rendered, is it possible to make it so that only the url changes, without a re-render? Or maybe 'use-query-params' is not so good idea to use here?

import React from 'react';
    import { StringParam, useQueryParam } from 'use-query-params';
    import cl from './Footer.module.scss';
    
    const Footer = () => {
          const [tab, setTab] = useQueryParam('ptab', StringParam);
        
          const handleClick = e => setTab(e.target.name);
        
          const getClass = name => {
            const values = ['tab1', 'tab2', 'tab3'];
        
            if (tab === name || (name === 'tab4' && (!tab || !values.includes(tab)))) return cl.active;
            return '';
          };
        
          return (
            <ul className={cl.footer}>
              <li>
                <button name='tab1' onClick={handleClick} className={getClass('tab1')}>
                  Tab1
                </button>
              </li>
              <li>
                <button name='tab2' onClick={handleClick} className={getClass('tab2')}>
                  Tab2
                </button>
              </li>
              <li>
                <button name='tab3' onClick={handleClick} className={getClass('tab3')}>
                  Tab3
                </button>
              </li>
            </ul>
          );
        };
        
        export default Footer;
Umbra
  • 53
  • 1
  • 4
  • Are you sure the ` – Terry Jan 07 '22 at 20:29
  • @Terry, yes, I have tried to do this, but the attempts are unsuccessful. Just need to add search param to the url string. For example, if there is already "?card=123", then when you click on the button it became "?card=123&ptab=tab3", without component re-render. – Umbra Jan 07 '22 at 21:11
  • Why dont you use the JS History Api? https://developer.mozilla.org/en-US/docs/Web/API/History_API – Michael Jan 07 '22 at 22:12
  • Here a simple example: https://codesandbox.io/s/hardcore-babycat-rz1v9?file=/src/App.js – Michael Jan 07 '22 at 22:16

1 Answers1

4

You can use the JS history API. Here a short example that should help you:

import "./styles.css";

export default function App() {
  const handleClick = (e) => {
    const url = new URL(window.location);
    url.searchParams.set("tab", e.target.name);
    window.history.pushState({}, "", url);
  };

  return (
    <ul>
      <li>
        <button name="tab1" onClick={handleClick}>
          Tab1
        </button>
      </li>
      <li>
        <button name="tab2" onClick={handleClick}>
          Tab2
        </button>
      </li>
      <li>
        <button name="tab3" onClick={handleClick}>
          Tab3
        </button>
      </li>
    </ul>
  );
}

Here the Link to the codesandbox: https://codesandbox.io/s/hardcore-babycat-rz1v9?file=/src/App.js:0-584

Michael
  • 947
  • 7
  • 17