Skip to content Skip to sidebar Skip to footer

Unable To Hide Some Components From Some Specific Routes

So I have this app which have the same layout in all routes except in two, Login and Register. I have been trying to have a totally separate layout for Login and Register routes bu

Solution 1:

  1. Use useLocation from react-router-dom to get the current pathname.
  2. With the .split() function you're able to get the last item.
  3. In the components that change depending on the location (Header, Footer, ...), create your condition (using ternary operator or switch case condition).

Examples :

Header.js (with ternary operator)

importReactfrom'react';
import { useLocation } from'react-router-dom';

exportdefaultfunctionHeader() {
  const path = useLocation().pathname;
  const location = path.split('/')[1];

  return (
    <div>
      {location === 'login' ? (
        <div></div>
      ) : (
        <div></div>
      )}
    </div>
  );
}

Footer.js (with switch case condition)

importReactfrom'react';
import { useLocation } from'react-router-dom';

importComponentA from'./components/ComponentA';
importComponentB from'./components/ComponentB';
importComponentC from'./components/ComponentC';

exportdefaultfunctionFooter() {
  const path = useLocation().pathname;
  const location = path.split('/')[1];

  constcheckLocation = (uri) => {
    switch (uri) {
      case'login':
        return<ComponentA />;
      case'register':
        return<ComponentB/>;
      case'about':
        return<ComponentC />;
      default:
        returnnull;
    }
  };

  return (
    <div>
      {checkLocation(location)}
    </div>
  );
}

Demo:Stackblitz

Solution 2:

Create two different layout , my suggestion is create src/layouts folder and save here your layouts. On your app.js or index.js use react router two switch between different layouts

Ps. Basically your sidebar, footer, navbar should be inside of your customize layout not on app.js or index.js

Post a Comment for "Unable To Hide Some Components From Some Specific Routes"