Reader small image

You're reading from  React Key Concepts

Product typeBook
Published inDec 2022
PublisherPackt
ISBN-139781803234502
Edition1st Edition
Right arrow
Author (1)
Maximilian Schwarzmüller
Maximilian Schwarzmüller
author image
Maximilian Schwarzmüller

Academind GmbH - Online Education: Bundling the courses and know-how of successful instructors, Academind strives to deliver high-quality online education. Online education, real-life success—that's what Academind stands for. Learn topics such as web development, data analysis, and more in a fun and engaging way. Maximilian Schwarzmüller: Since the age of 13, Maximilian Schwarzmüller has never stopped learning new programming skills and languages. In the early days, he started creating websites for friends and for fun. This passion has remained and shaped his decision to work as a freelance web developer and consultant. The success and fun he has in this job is immense and really keeps that passion alive. Although he started web development on the backend (PHP with Laravel and NodeJS), he has increasingly become a front-end developer using modern frameworks such as React, Angular, or VueJS 2 in a lot of projects. As a self-taught developer, he had broadened his horizon by studying business administration, resulting in a master's degree. This enabled him to work in a major strategy consultancy as well as a bank. Whilst learning and developing his skills, he realized that he enjoyed development more than these fields. As a self-taught professional, Max is familiar with the difficult topics when learning new or improving on already-known languages. This background and experience enables him to focus on the most relevant key concepts and topics. His track record is the best proof of that. Whether working as a development instructor or teaching business administration, he always receives great feedback. The most rewarding experience is to see how people find new and better jobs, build awesome web applications, acquire amazing projects, or simply enjoy their hobby with the help of his content.
Read more about Maximilian Schwarzmüller

Right arrow

7. Portals and Refs

Learning Objectives

By the end of this chapter, you will be able to do the following:

– Use direct DOM element access to interact with elements

– Expose the functions and data of your components to other components

– Control the position of rendered JSX elements in the DOM

Introduction

React.js is all about building user interfaces, and, in the context of this book, it's about building web user interfaces specifically.

Web user interfaces are ultimately all about the Document Object Model (DOM). You can use JavaScript to read or manipulate the DOM. This is what allows you to build interactive websites: you can add, remove, or edit DOM elements after a page was loaded. This can be used to add or remove overlay windows or to read values entered into input fields.

This was already discussed in Chapter 1, React – What and Why, and, as you learned there, React is used to simplify this process. Instead of manipulating the DOM or reading values from DOM elements manually, you can use React to describe the desired state. React then takes care of the steps needed to achieve this desired state.

However, there are scenarios and use cases wherein, despite using React, you still want to be able to directly reach out to specific DOM elements...

A World without Refs

Consider the following example: you have a website that renders an input field, requesting a user's email address. It could look something like this:

Figure 7.1: An example form with an email input field

The code for the component that's responsible for rendering the form and handling the entered email address value might look like this:

function EmailForm() {
  const [enteredEmail, setEnteredEmail] = useState('');
  function updateEmailHandler(event) {
  setEnteredEmail(event.target.value);
  }
  function submitFormHandler(event) {
  event.preventDefault();
  // could send enteredEmail to a backend server
  }
  return (
  <form className={classes.form} onSubmit={submitFormHandler}>
    <label htmlFor="email">Your email</label>
    <input type="...

Refs versus State

Since refs can be used to get quick and easy access to DOM elements, the question that might come up is whether you should always use refs instead of state.

The clear answer to this question is "no".

Refs can be a very good alternative in use cases like the one shown above, when you need read access to an element. This is very often the case when dealing with user input. In general, refs can replace state if you're just accessing some value to read it when some function (a form submit handler function, for example) is executed. As soon as you need to change values and those changes must be reflected in the UI (for example, by rendering some conditional content), refs are out of the game.

In the example above, if, besides getting the entered value, you'd also like to reset (i.e., clear) the email input after the form was submitted, you should use state again. While you could reset the input with the help of a ref, you should not do that...

Using Refs for More than DOM Access

Accessing DOM elements (for reading values) is one of the most common use cases for using refs. As shown above, it can help you reduce code in certain situations.

But refs are more than just "element connection bridges"; they are objects that can be used to store all kinds of values—not just pointers at DOM objects. You can, for example, also store strings or numbers or any other kind of value in a ref:

const passwordRetries = useRef(0);

You can pass an initial value to useRef() (0 in this example) and then access or change that value at any point in time, inside of the component to which the ref belongs:

passwordRetries.current = 1;

However, you still have to use the current property to read and change the stored value, because, as mentioned above, this is where React will store the actual value that belongs to the Ref.

This can be useful for storing data that should "survive" component re-evaluations...

React and Where Things End up in the DOM

Leaving the topic of refs, there is one other important React feature that can help with influencing (indirect) DOM interaction: Portals.

When building user interfaces, you sometimes need to display elements and content conditionally. This was already covered in Chapter 5, Rendering Lists and Conditional Content. When rendering conditional content, React will inject that content into the place in the DOM where the overall component (in which the conditional content is defined) is located.

For example, when showing a conditional error message below an input field, that error message is right below the input in the DOM:

Figure 7.4: The error message DOM element sits right below the <input> it belongs to

This behavior makes sense. Indeed, it would be pretty irritating if React were to start inserting DOM elements in random places. But in some scenarios, you may prefer a (conditional) DOM element to be inserted...

Summary and Key Takeaways

  • Refs can be used to gain direct access to DOM elements or to store values that won't be reset or changed when the surrounding component is re-evaluated.
  • Only use this direct access to read values, not to manipulate DOM elements (let React do this instead).
  • Components that gain DOM access via refs, instead of state and other React features, are considered uncontrolled components (because React is not in direct control).
  • Prefer controlled components (using state and a strictly declarative approach) over uncontrolled components unless you're performing very simple tasks such as reading an entered input value.
  • Using forward refs, you can also expose features of your own components such that they may be used imperatively.
  • Portals can be used to instruct React to render JSX elements in a different place in the DOM than they normally would.

What's Next?

At this point in the book, you've encountered many...

Apply What You Have Learned

With this newly gained knowledge about refs and portals, it's again time to practice what you have learned.

Below, you'll find two activities that allow you to practice working with refs and portals. As always, you will, of course, also need some of the concepts covered in earlier chapters (e.g., working with state).

Activity 7.1: Extract User Input Values

In this activity, you have to add logic to an existing React component to extract values from a form. The form contains an input field and a drop-down menu and you should make sure that, upon form submission, both values are read and, for the purpose of this dummy app, output to the browser console.

Use your knowledge about Refs and uncontrolled components to implement a solution without using React state.

Note

You can find the starting code for this activity at https://packt.link/PAvKn. When downloading this code, you'll always download the entire repository. Make sure...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React Key Concepts
Published in: Dec 2022Publisher: PacktISBN-13: 9781803234502
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 $15.99/month. Cancel anytime

Author (1)

author image
Maximilian Schwarzmüller

Academind GmbH - Online Education: Bundling the courses and know-how of successful instructors, Academind strives to deliver high-quality online education. Online education, real-life success—that's what Academind stands for. Learn topics such as web development, data analysis, and more in a fun and engaging way. Maximilian Schwarzmüller: Since the age of 13, Maximilian Schwarzmüller has never stopped learning new programming skills and languages. In the early days, he started creating websites for friends and for fun. This passion has remained and shaped his decision to work as a freelance web developer and consultant. The success and fun he has in this job is immense and really keeps that passion alive. Although he started web development on the backend (PHP with Laravel and NodeJS), he has increasingly become a front-end developer using modern frameworks such as React, Angular, or VueJS 2 in a lot of projects. As a self-taught developer, he had broadened his horizon by studying business administration, resulting in a master's degree. This enabled him to work in a major strategy consultancy as well as a bank. Whilst learning and developing his skills, he realized that he enjoyed development more than these fields. As a self-taught professional, Max is familiar with the difficult topics when learning new or improving on already-known languages. This background and experience enables him to focus on the most relevant key concepts and topics. His track record is the best proof of that. Whether working as a development instructor or teaching business administration, he always receives great feedback. The most rewarding experience is to see how people find new and better jobs, build awesome web applications, acquire amazing projects, or simply enjoy their hobby with the help of his content.
Read more about Maximilian Schwarzmüller