I started learning react about a week ago, taking a Code Academy course, so please be patient with my potentially very ugly code below. I recently finished working on my portfolio and one of the most exciting elements that I created is the navigation system. I developed the navigation method with little to no guide, just the knowledge that I gained from my Code Academy courses. I wanted to make an easy to follow guide so that people new to React can make their own navigation bar, just like me! The code may look ugly to the React pro out there, but I also want to hear critiques of my code, so please feel free to comment!
- The first thing I did was create a static navigation bar with “Home”, “About Me”, and “Hobbies” in the main navigation list, then created a sub navigation list under “About Me” and “Hobbies”. This was simple HTML and CSS and there are about a million examples, so I will not be showing you my specific code. A good source on how to build a nav bar can be found at the w3schools.com website.
- In the initiating ul tag I placed an event handler for an “onClick” event that sent you to the internal function this.handleClick.
- I gave each clickable element a specific id that will later be evaluated to determine the page to show.
- I wrote the handle click function to send that specific id as a property to the parent element, but only if the associated element had an id. I had to use e.target.id to pull this information. I think I should have used a value instead of id, but for some reason I couldn’t get this to work.
- I created the constructor and binded the handleClick function. Still not sure why these steps are required, I’ll need to continue doing research.
- I rendered the NavBar in the header of App.js, then assigned the function this.changePage on a click event.
- I wrote the changePage function to take in a newPage element, then reset the page if the new page requested was different then the current page. I’ll show the code along with the constructor below.
- I built the constructor and set the initial state to be the Home page, as well as binded the changePage function.
- Below the header, I created a new element to hold the contents of my page. Inside of this element, I called a function that will display my page.
- I built the PageDisplay function on several if-else statements. One for each page, but I will only show you a couple because it is a lot of the same code (again, I can probably clean this up with more than a week’s worth of experience).
- I’d like to show you the whole code, but it is mostly straight forward, except what I did in the App component. Here is the App component for your viewing pleasure. Please let me know what you think!
We're in this together
Level up every day