On to project 8 of 100. Today I wanted to practice conditionally rendering a navbar and a page component. It's called a single page application for a reason, right?
This time I did things in the old school way- the .NET way- and just changed the page that was rendering inside of a page container. That means the navbar never leaves and (obviously, it's React) the page itself never refreshes.
Design
To accomplish this I build two components- <Navbar />
and <PageContainer />
. I also built three pages: components that would live inside the div. I cleverly named them Page1, Page2, and Page3.
In the App component's state I created an activePage property that was set to 1 by default. This keeps track of which page we are rendering inside the and also tells the which nav item is selected, so that it appears 'selected' with a darker background color.
Obviously, switching between a couple of pages in pure HTML is child's play. Or at least it's easy and doesn't involve code. In React, doing this is a worthwhile exercise, especially when updating multiple components at the same time given a change in state.
Challenges
The two challenges I met while creating this project were the following:
-
The
this
keyword and props - How annoying is it that when you're passing a state property to a component you can forget thethis
keyword and the entire program crashes? Though it's always a good reality-check about Javascript scope when it happens. -
Passing data from a component to App state - This is a more understandable mistake, as without React Hooks it's hard to share data from a component with the app.
I solved the problem by reading this awesome free article from Pluralsight and then in the child component passing each nav item a custom attribute called
item
. Next, I created a function in the App component to set state based one.target.getAttribute("item")
. Pretty cool, eh? I expect there is a more sophisticated way of doing this than literally reading the html attribute from a component- but sometimes it's fun to do it the old school way.
Alright, that's it for today!
*Github repo here
*Deployed app here
Follow 4 follow me on my new development-only Twitter:
twitter.com/jwhubert91
Top comments (0)