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.
Section overview
5 resourcesExplores 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article