loading...
Cover image for Single-Page Applications using React Router

Single-Page Applications using React Router

dylanmesty profile image Dylan Mestyanek ・6 min read

So, if this is your first time diving into this blog — I’ll explain a quick summary. I’ve been a Lambda School student for about the past 7 weeks. I’ve done journaling, and milestone planning, during my time at the school; however, I’ve been meaning to document the time spent there. Starting last week I published my first blog post — and from then on out, I’m posting a weekly update about my time at Lambda. With that said, here’s my weekly re-cap covering single-page applications!

Week 7: React Router

This week we explored the world of React Router. I learned the difference between client-side, and server-side routing. Essentially, React Router allows for client-side routing, an extremely efficient “cheat code”, if you will. Standard server-side routing, requires the page to reload, and require a server to render different pages of your website, or web application. Using React Router, React.js has a built-in package, where you can locally route between pages on the client’s side of the application, resulting in the lack of need to refresh the page, or fetch any non-local information. So awesome! Here's how the week broke down:

Day 1: Intro to React Router

This day was a great first impression of working with React Router. We learned the basics of installing, and importing React Router. With the package, you have access to a ton of key components. Some of the basics are: Route, Link, BrowserRouter.

Essentially, importing BrowserRouter allows your application to use React Router. I suppose you could say it’s the unlock key. The magical pass. The secret passage! Wrapping your React application in this, grants unlimited possibility!

Next is Route. What helped me comprehend the purpose of Route was the fact that it grants access to that path. In essence, a Link will take you to the Route. Route allows you to specify a different URL, and as a result, loads different content, that is connected to that route. For example, you could have a home page: https://www.test-website.com/ and that would render something similar to a main page.

Now, suppose you had different content, maybe a contact page, or an about page, with information completely different than the home page. You could use Route to specify your new URL destination: https://www.test-website.com/about. With everything done locally, nothing refreshes, it just re-renders new content to the screen. Super fun! Endless amount of possibilities with this!

Lastly was Link to conclude the first day of single-page applications. In short, Link's are just anchor tags, with some extra functionality built into the React component. A link allows you to specify your desired route location, and set the destination as the anchor tag’s href attribute. With routes and links, everything became suddenly so efficient!

Day 2: React Router continued..

This day was when it got a bit more in-depth, and a tad more confusing. Yet, it was still extremely fun! We covered the difference between component and render in the Route component. Also touching on which props are automatically passed with Route by default. Ending off the day with the NavLink component — now that is what I call a nifty component.

render and component are real similar with one helpful difference: the render attribute allows you to pass props to the component you’re rendering. In React Router, a Route receives three props automatically, but using the component attribute, you don’t have the option to pass any additional props, such as state, or a function you have stored in that file. render allows you to simply pass those pieces of code in as props, similar to any other component — in addition to passing in the default Route props, which are match, history, and location. I am relatively still unsure of the functionality of all of these props, so I shall save that for a different day. Below is an example of how two different routes would look: one route using component and one using render.

<Route path="/pathHere" component={ExampleComponent} />

and

<Route path="/pathHere" render={(props) => 
   <ExampleComponent {...props} exampleProps={exampleProps} />
}/>

In render example, to receive the props from the Route you simply just take in the props with the rest operator ... and you’re all set! All the tough work is done for you — so cool!

The NavLink component is really neat, as it only has one major difference in comparison to a standard Link component — activleStyle or activeClassName. In short, a NavLink receives one of these attributes, which is either inline styles, or a class name you are adding to the component. These styles are only applied when that link is being used/active.

The result? You get some fancy styling on your navigation links! For example, you could have the Home tab highlighted only when you’re on that page, and the About tab highlighted only when you’re viewing the about page — This pumped me up!

Day 3: Form Management in React

Let me start by saying, Forms have so much to them, I won’t go into an entire 8-page review on how to use forms in React, haha! I will just cover some foundational principles in this section.

In summary, we learned to use the form, label, and input elements to create a nice, simple form. The form needs two functions to make it functional: onChange and onSubmit. In my experience, these functions are typically named handleChange and handleSubmit. handleChange is responsible for setting your React state, to the value that is placed in the input element.

import React, { useState } from "react";

const Form = props => {

  const [user, setUser] = useState({
    id: '',
    name: '',
    email: ''
  });

  const handleChange = (event) => {
    const { name, value } = event.target;
    setUser({...user, [name]: value});
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    setUser({
      name: '',
      email: ''
    });
  };

  return (
    <form onSubmit={(event) => handleSubmit(event)}>
      <label>
        Name:
        <input
          onChange={(event) => handleChange(event)}
          name="name"
          type="text"
          value={user.name}
         />
     </label>

     <label>
       E-Mail:
       <input
         onChange={(event) => handleChange(event)}
         name="email"
         type="email"
         value={user.email}
       />
     </label>

     <button>Submit!</button>
   </form>
  );
}
export default Form;

We have a form that has a user state, which holds all of the input values. A handleChange function which is setting the value of the input field, to the object with that key-value pair within the user state. handleSubmit is simply clearing the form, after submitting it. Below that, there is the actual form being rendered. One important attribute to take note of is the value on each input. This value attribute is stating that, whatever the value of the user state is, display that value inside of the input. That way you can view what you are typing, in real-time!

handleSubmit is responsible for submitting the data to an API, using a function like axios.post() and also clearing the input fields, and rendering a fresh form to use. I view handleSubmit as the “farewell” to the form you were working on — see you later!

e.preventDefault(); or event.preventDefault(); prevents the page from reloading when you submit the form, and potentially losing all of your input values.

Day 4: Advanced Form Management with Formik and Yup

If I was to properly sit down, and explain everything about Formik and Yup to you, I’d essentially be re-teaching the entire lecture — haha! These tools are so, so powerful, but I will do my best to keep it concise.

Formik is a library that can be used in React which essentially makes your forms equally as efficient, but eliminating a ton of extra code. It has built-in Form and Field components, with a ton of unique add-ons to them, making your life way easier! I highly suggest taking a peek at what Formik is capable of. I intend to use it a lot more often!

Yup was also really fun to explore with — essentially, it allows you to implement form validation. You know, those super cool error messages that say, Woops! Your password doesn’t meet the requirements. or, That’s an invalid e-mail format! Yup polishes up your forms, and makes them appear really complete, and finished, from a user’s standpoint. A ton of creative ideas, and possibilities using Yup. I really enjoyed learning about it!

Review

This week was really informative and definitely tested my skills a bit. Before this week, I had yet to struggle with any of the curriculum, but this week definitely put up a fight! However, by the end of the week, I felt confident with implementing what I learned. React Router is an awesome tool for loading different pages quickly, and efficiently. Forms are a core staple in a lot of websites, and web applications, and Formik helps make it real simple to build awesome forms! Additionally, using Yup, you can spice up your forms so they are organized, clean, structured, and easy to follow!

Biggest Take Away

As topics get increasingly more in-depth, and difficult, it is not uncommon to struggle and need more than a few hours a day to fully grasp a concept. This week was a humbling experience, and taught me that some concepts need extra attention to completely understand. Be patient, and practice as much as you can. Always implement what you learn, try to break it. Fix it. Learn from the mistakes. Rinse, and repeat!

Posted on by:

dylanmesty profile

Dylan Mestyanek

@dylanmesty

Full Stack Web Developer Student — Documenting my journey and sharing what I’ve learned during my time studying code!

Discussion

markdown guide
 

Really nice writeup. I am assuming they talked about controlled components and uncontrolled components when they touch upon forms.

 

The idea was touched upon, but was not spoken about in depth. That's definitely a topic I need to review!