Reader small image

You're reading from  Full-Stack Flask and React

Product typeBook
Published inOct 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803248448
Edition1st Edition
Right arrow
Author (1)
Olatunde Adedeji
Olatunde Adedeji
author image
Olatunde Adedeji

Olatunde Adedeji is a seasoned web developer with over 15 years of experience in developing dynamic and detail-oriented enterprise web applications. Along with his extensive experience in developing, maintaining and supporting mobile, web and enterprise applications in Python, Go and JavaScript, Olatunde has consistently delivered excellent services, as team lead, team member or in consultancy capacity. Olatunde is proficient in application design and solution blueprinting; including mastery of application development tools such as: Flask, Django, Gin, React, and NodeJS. When not weaving the web and playing chess, Olatunde spends time with his wife, Adedoyin and two daughters, Mitchelle and Mabel.
Read more about Olatunde Adedeji

Right arrow

Working with React Router and Forms

React Router is a library for client- and server-side routing. Imagine the usual way websites work; when you click on a link, your browser sends a request to the web server, receives a bunch of data, and then takes time to process everything before finally displaying the content of the new page.

You will get the same experience every time you request a new page from the website. With client-side routing, things get way smoother! Instead of going through that whole process every time you click a link, your web app can update the URL instantly without bothering the server for a new document. This means your web app can quickly show you a new part of the app without any delays. This and more is what React Router offers.

In this chapter, we will explore React Router v6 as a magical tool to handle navigation. You can also use React Router for data fetching but we will limit our scope to component navigation in this book. You will implement simple...

Technical requirements

The code for this chapter can be found at https://github.com/PacktPublishing/Full-Stack-Flask-and-React/tree/main/Chapter06.

Due to page constraints, some of the code blocks have been snipped. Please refer to GitHub for the complete code.

Routing with React Router

Routing in a React web application is the ability to navigate seamlessly to and from multiple application components, URLs, pages, and resources, both internal and external. By default, React doesn’t include page routing in its library. And as a matter of fact, React’s main goal is to allow developers to design the display of the view of a single-page web application.

We all know web applications require multiple views, hence the need for an external library such as React Router to allow for component navigation. Working with a large application would require multiple specialized views. This means we have to solve the problem of navigation left untreated with the React library, but this is where React Router comes in.

React Router is an open source package that’s used for component-based routing in React applications. It is popular among React developers and widely used in various React projects. Interestingly, you can use React...

Adding React Router in React

You need to install React Router to use it in your project. We are going to build the navigation features for the Bizza project to connect different components. The navigation tabs will consist of the home, about, speakers, events, sponsors, and contact pages. Let’s start coding by entering this command in the project directory’s Terminal:

npm install react-router-dom@latest

Once we have the package installed in the root directory of our project, we can create the home, about, speakers, news, and contact pages components.

Now, we will add content to each of these components:

  • Inside src/pages/HomePage/HomePage.js, add the following code snippet:
    import React from 'react';const HomePage = () => {    return <div> Home page </div>;};export default HomePage;
  • Inside src/pages/AboutPage/AboutPage.js, add the following:
    import React from 'react';const AboutPage = () => {...

Handling dynamic routes

In web application development, a dynamic route refers to a route that employs a placeholder to represent a changing value. This placeholder can be used to handle various dynamic content. You can have placeholders such as speakerId, productId, postId, and so on to represent the changing value.

For instance, let’s consider the preceding speakers route we updated with /speakers/:speakerId. It is conventional to add a colon in front of a dynamic route, like so: :speakerId. So, how can we retrieve this value of speakerId from the URL? This is where the useParams hook comes in.

Using useParams

The useParams hook in React Router provides access to the dynamic parameters extracted from a route. These parameters are the values that correspond to the placeholders in the path of a dynamic route.

For instance, in the following code snippet, the useParams hook is used to retrieve SpeakerId from the /speakers/:speakerId route. The following code shows...

Using forms in React

Conventionally, forms are used to collect user inputs. There is no serious production-grade web application without forms. Using forms in React is slightly different from using HTML form elements. If you have developed React applications for a while, this might not be new to you.

The subtle difference between the elements of React forms and those of normal HTML forms is due to the unique way React handles the internal state of forms. The HTML DOM manages the internal states of native HTML form elements in a browser DOM way. On the other hand, React handles form elements through its components’ state.

So, what is this state all about? The state we are talking about is an object that holds user inputs before form submission. Form elements have an internal state that prevents data loss before you submit user input across the processing channel.

Having laid down the background for the internal state management of form elements, let’s quickly...

Controlled and uncontrolled form components

So far in this book, we have become familiar with components and how they are the building blocks of any React application. When you blend pieces of independently designed components, you get either a UI component or a full-fledged React web application, depending on what you are working on.

The component-driven approach of React is not going to change anytime soon. Building quality UIs for applications is what React does best. You are going to need a high-performant form one way or the other in your career as a developer, and React has you covered with two approaches to building air-tight form components that prevent data loss and improve user experience regarding form interaction.

These two approaches are controlled and uncontrolled form components. Let’s start with controlled form components so that we have a sufficient understanding of how they are implemented and why they are the React-recommended approach to form handling...

Handling user input – Input, TextArea, and Select

Handling React form elements is slightly different from the way non-React applications handle user inputs. In this section, we will look at common form elements that are used in handling user input while following React best practices.

Input

Input fields in the form are the most widely used tags in any web application. An input field allows the collection of user data. Input fields have different types depending on their purpose in a form. In the controlled input form element, the component state is always set using a value or checked attribute on the form input field. You also have a callback that listens to the change in value as a result of user input.

With the input type radio and checkbox, we use the checked attributes. To access the value of the input field, we can use event.target.checked.

TextArea

Textarea is a tag that allows users to write multi-line characters of text. Textarea is usually used to collect...

Validating and sanitizing users’ data in React

Validation is a process that ensures user data quality, integrity, and an appropriate format that’s expected for a system. You can never trust data provided by users of your application blindly. While we expect them to trust our code, we can’t reciprocate that trust by not guiding them on how our forms and form data should be treated.

Starting as a junior developer, the phrase Don’t ever believe a user would always do the right thing with your form will forever ring true. You can never trust user data as is. Data that comes from users has to be thoroughly scrutinized and cleaned and ensured it is in the desired format.

Forms fields are the open window into everything you might call the backend in web development. So, trusting user input without some rules in place could be detrimental to your sanity as a developer and to the healthy condition of your web application.

There are always standard-practice...

Summary

In this chapter, we discussed two vital concepts in React: forms and routing. We highlighted the subtle difference in the forms that are set up in non-React and React applications. React provides tons of improvement in how it handles form elements through the use of controlled and uncontrolled form components to enhance the user experience.

Then, we delved into validation concepts and how you can implement validation rules in React. We then spoke about React Router. We demonstrated how React Router, a third-party library, enables us to navigate complex React applications. We discussed the use of Route, Links, and nested Routes and explored how they are used in a React project.

In the next chapter, we will learn about and understand how to implement testing in React applications. Testing is an essential part of software development as it ensures the components of an application work as they should and that the relevant best practices are observed in development.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Full-Stack Flask and React
Published in: Oct 2023Publisher: PacktISBN-13: 9781803248448
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Olatunde Adedeji

Olatunde Adedeji is a seasoned web developer with over 15 years of experience in developing dynamic and detail-oriented enterprise web applications. Along with his extensive experience in developing, maintaining and supporting mobile, web and enterprise applications in Python, Go and JavaScript, Olatunde has consistently delivered excellent services, as team lead, team member or in consultancy capacity. Olatunde is proficient in application design and solution blueprinting; including mastery of application development tools such as: Flask, Django, Gin, React, and NodeJS. When not weaving the web and playing chess, Olatunde spends time with his wife, Adedoyin and two daughters, Mitchelle and Mabel.
Read more about Olatunde Adedeji