Aakash_Sardana
Aakash_Sardana

Reputation: 270

Hiding common component on Not Found Page in React-Router

In my react app, there is a common header which is outside of my Routes and other components are loaded based on routing.

      <React.Fragment>
            <Header />
            <div className="container dflex">
              <Switch>
                <Route path="/money-transfer" component={MoneyTransfer} />
                <Redirect from="/" to="/money-transfer" exact />
                <Route path="/dmt" exact component={MyDmt} />
                <Route component={NoFound} />
              </Switch>
          </div>
      </React.Fragment>

I want to also hide my header when NoFound Page is rendered. What can be the best possible solution for this ?

Upvotes: 2

Views: 471

Answers (2)

Dixit Savaliya
Dixit Savaliya

Reputation: 413

Try this,

  <React.Fragment>
                 let HideHeader = NoFound ? null : <Header />
                 {HideHeader}
                <div className="container dflex">
                  <Switch>
                    <Route path="/money-transfer" component={MoneyTransfer} />
                    <Redirect from="/" to="/money-transfer" exact />
                    <Route path="/dmt" exact component={MyDmt} />
                    <Route component={NoFound} />
                  </Switch>
              </div>
          </React.Fragment>

Upvotes: 1

tarzen chugh
tarzen chugh

Reputation: 11257

You could Redirect to a particular route when no route is matched and then check for that route in Header to hide that component.

 <Switch>
    <Route path="/money-transfer" component={MoneyTransfer} />
    <Redirect from="/" to="/money-transfer" exact />
    <Route path="/dmt" exact component={MyDmt} />
    <Route component={NoFound} />
 </Switch>

function NoFound() {
  return <Redirect to="/notfound" />;
}

// Header.js

const Header = props => {
  const { location } = props;

  if (location.pathname.match(/notfound/)) {
    return <NotFoundRoute />;
  }
  return <h3>I am the Header</h3>;
};

export default withRouter(Header);

// NotFoundRoute.js

function NotFoundRoute() {
  return <div>No Route Found</div>;
}

Working code sample codesandbox link

Hope that helps!!!

Upvotes: 2

Related Questions