React.js / React Advanced Concepts

Working with React Fragments and Refs

In this tutorial, we will explore React Fragments and Refs. You will learn how fragments can reduce unnecessary DOM nodes and how refs can be used to control specific elements.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explores advanced concepts in React, including higher-order components and portals.

Working with React Fragments and Refs

1. Introduction

In this tutorial, we'll delve into React Fragments and Refs. React Fragments help in grouping a list of children without adding extra nodes to the DOM, which can help optimize your applications. Refs, on the other hand, allow us to access DOM nodes directly within React. This can be useful when you need to change an element's value or trigger an imperative action.

What you'll learn:
- How to use React Fragments
- How to access and manipulate DOM nodes with Refs.

Prerequisites:
- Basic understanding of JavaScript and React.

2. Step-by-Step Guide

React Fragments

Fragments are used when a component needs to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

Example:

import React, { Fragment } from 'react';

function Example() {
  return (
    <Fragment>
      <p>This is a paragraph.</p>
      <p>This is another paragraph.</p>
    </Fragment>
  );
}

export default Example;

In this example, two paragraphs are returned without a parent container. This reduces unnecessary DOM nodes.

React Refs

Refs in React allows us to access and interact with DOM nodes or React elements created in the render method.

Example:

import React, { useRef } from 'react';

function TextInput() {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus the input</button>
    </div>
  );
}

export default TextInput;

In this example, the inputRef is attached to the input element. When the button is clicked, the input receives focus.

3. Code Examples

Example 1: Fragment

import React, { Fragment } from 'react';

function FragmentExample() {
  return (
    <Fragment>
      <h1>Title</h1>
      <p>Description</p>
    </Fragment>
  );
}

export default FragmentExample;

In this example, the Fragment wraps around the h1 and p elements, allowing them to be returned as a group without adding an unnecessary DOM node.

Example 2: Ref

import React, { useRef } from 'react';

function RefExample() {
  const myRef = useRef(null);

  const handleClick = () => {
    myRef.current.value = 'Hello, World!';
  };

  return (
    <div>
      <input ref={myRef} type="text" />
      <button onClick={handleClick}>Set Input Value</button>
    </div>
  );
}

export default RefExample;

In this example, the myRef is attached to the input element. When the button is clicked, the value of the input changes to 'Hello, World!'.

4. Summary

In this tutorial, we've learned how to use React Fragments to group a list of children without adding extra nodes to the DOM. We've also learned how to use Refs to access and manipulate DOM nodes directly within React.

Next Steps:
- Practice using fragments and refs in your own projects.
- Try to build a small application which uses both concepts.

Additional Resources:
- React Documentation
- React Fragments
- React Refs and the DOM

5. Practice Exercises

Exercise 1: Create a component that uses a fragment to return an unordered list with five list items.

Exercise 2: Create a component with a text input and a button. When the button is clicked, the text input should be cleared.

Exercise 3: Combine the first two exercises. Create a component with a text input, a button, and a list. When the button is clicked, the value of the text input should be added as a new list item. The text input should then be cleared. Use refs and fragments as needed.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help