Navigating to Nested React Components

Grishma
2 min readAug 13, 2022

--

I built a portfolio website using React and Material UI.

My Portfolio website

It has a simple structure of nested Components. Three different Components are included inside the `App` Component — NavBar, Home and Contact. The code looks like this:

While setting-up BrowserRouter, it was easy to access the parent Component `App`.

To navigate between different Components in React (or different views) we can use BrowserRouter with path as the URL of that view/component.

But, when I tried to navigate directly to a Component inside my App Component, like `Contact section` of my page, by using the link “mySite.com/contact” it did not navigate, instead it opened a fresh view showing only the Contact page.

To resolve this issue, the first method I tried was using HashTag (‘#’) and Component ids:

<div id="contact" className="Contact"/> and used url as “mySite.com/#contact”.

But this did not work on page load, as it was taking me to the start of App Component every time page re-loaded.

I was able to find a solution to this using React Lifecycle and function `scrollIntoView`

Once my App Component was rendered, using componentDidMount(), I implemented a function which read browser url and scrolled to that particular Component using its id. Its code looks like this:

There must be many ways to tackle this issue, I found one of them. Do let me know if you have come across similar situations and solutions.

--

--