How to Not Render a Component on a Particular Page in React


9 Shares
facebook sharing button Share
twitter sharing button Tweet
linkedin sharing button Share
pinterest sharing button Pin
email sharing button Email
sharethis sharing button Share

Problem: Layout components rendering on pages you don't want them to.

 Download The Notes Here


I was recently working on a project in React, and I had two different component folders: Pages and Layout. Inside the Layout folder, I had my Navbar component and my Footer component. The Navbar and Footer both rendered nicely on all my pages, which is what I wanted. However, I wanted my landing page to have a different layout and did not want to have the Navbar and Footer on my landing page. But after creating my landing page, sure enough, the Navbar and Footer were there.

Landing Page with Navbar

Landing Page with Footer


I know that there are a number of ways to approach this. You can see a variety of approaches on Stack Overflow, as I did. I also tried different approaches, but did not succeed. I was able to find a solution to this with the help of React Helmet, a reusable React component that is used to manage changes to the document head. I like React Helmet, and I was already using it on this project to manage the titles that appear in the browser tabs.

So, as I was already using React Helmet, I decided to try to use it for this too. The code below is a simplified version of the code for my landing page component (I removed the code for the component, since that is not the focus here), which I called Home.js.

After installing React Helmet, I then brought it into my landing page, Home.js (line 3). Wrapping the title element inside the Helmet element (lines 9-11) allows us to give a title that will appear on the tab in the browser. This is what I was already using React Helmet for.

Code Detail


In order to deal with my component issue, I was able to use React Helmet to add CSS to only this component (lines 7-12). Specifically, I used the "display" property and set that to "none" for both the Navbar and Footer components (lines 8-10). And that's it. That fixed it. If I had done this in App.css (which is what I used for my project's global styles), then the styles would have gotten applied to all of the components, which is not what I wanted. Then the Navbar and Footer would not show on any of the pages. React Helmet allowed me to apply this CSS to only my landing page, which is what I wanted.

Code Detail


And as you can see, I no longer have the Navbar and Footer showing in my landing page, which is what I wanted.

Landing Page