Introduction and Topic Overview

Welcome! Today's journey explores how React handles user input in functional components. We will cover Refs, a feature for managing certain functionalities, as well as the difference between controlled and uncontrolled components.

Understanding User Input in Functional Components

User input is crucial for all interactive web applications. React handles this input elegantly, using state, props, and hooks. Let's construct a Greeting function component that presents a dynamic message based on user input.

In this component, useState is used to declare the state variable name. The name stores the value of the input element and updates whenever the text input changes:

import React, { useState } from 'react';

function Greeting() {
  const [name, setName] = useState('');

  return (
    <div>
      <h1>Hello, {name}!</h1>
      <input
        type="text"
        value={name}
        onChange={(event) => setName(event.target.value)} // Updates `name` upon typing in the input
      />
    </div>
  );
}
Introduction to Refs in React

Refs or references in React provide a way to access and interact with DOM nodes or React elements directly within your components. This is especially handy in cases where you want to change the child component without making use of props or triggering a re-render.

Refs are created by invoking the useRef hook provided by React. Here's how we do it:

const myRef = useRef();

Notice that we call useRef() without passing any arguments. This results in myRef.current getting initialized with the value of null. The current property is mutable; it's created specifically for you to assign it a persistent value that doesn't trigger a re-render, thereby allowing the value to persist across renders.

Let’s see how the ref is used with an actual element in JSX by using the ref attribute, which takes the ref created above as its value:

<input ref={myRef} type="text" />

The ref attribute acts like a tether, linking the myRef ref to the input field, hence allowing us detailed access to this specific instance of the input field across renders. It lets myRef.current point to the corresponding DOM node, here an HTMLInputElement, providing a way to read from or write to it.

Following is a brief example:

import React, { useRef } from 'react';

function Greeting() {
  const nameRef = useRef(); // nameRef.current is initialized as null

  return (
    <div>
      <h1>Hello, {nameRef.current && nameRef.current.value}!</h1>
      <input ref={nameRef} type="text" /> {/* ties nameRef to the input field */}
    </div>
  );
}

As we can see, the text input is now linked with nameRef. Although in this form React does not automatically capture and update its value, opening up interesting possibilities we'll look at next.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal