<Fragment> (<>...</>)

<Fragment>, যেটা বেশিরভাগ সময় <>...</> সিনট্যাক্স ব্যবহার করে প্রকাশ করা হয়, আপনাকে একটা wrapper নোড ছাড়াই এলিমেন্ট গ্রুপ করার সুবিধা দেবে।

Fragment-এ ref-ও দেওয়া যায়। এর সাহায্যে কোনো wrapper এলিমেন্ট যোগ না করেই ভেতরের DOM নোডগুলোর সাথে কাজ করা যায়।

<>
<OneChild />
<AnotherChild />
</>

রেফারেন্স

<Fragment>

যেসব ক্ষেত্রে আপনার একটি মাত্র এলিমেন্ট লাগবে <Fragment> এর মধ্যে একাধিক এলিমেন্ট গ্রুপ করে wrap করে ফেলুন। Fragment এর মধ্যে গ্রুপ করা হলে ফলাফলে যে DOM পাওয়া যায় তার উপর কোন প্রভাব পড়ে না; গ্রুপ করা না হলে যেমন হত ঠিক তেমনি ঘটে। বেশিরভাগ ক্ষেত্রে খালি JSX ট্যাগ <></> কে <Fragment></Fragment> প্রকাশ করতে সংক্ষেপে ব্যবহার করা হয়।

Props

  • অপশনাল key: যেসব Fragment স্পষ্টভাবে <Fragment> সিনট্যাক্স দিয়ে ডিক্লেয়ার করা হয়, তাদের key থাকতে পারে।
  • অপশনাল ref: একটি ref অবজেক্ট (যেমন useRef থেকে পাওয়া) অথবা callback ফাংশন। React ref-এর মান হিসেবে একটি FragmentInstance দেয়, যার মেথডগুলো দিয়ে Fragment-এর মধ্যে থাকা DOM নোডগুলোর সাথে কাজ করা যায়।

সতর্কতা

  • আপনি যদি একটা ফ্র্যাগমেন্টে key পাস করতে চান, আপনি <>...</> সিনট্যাক্স ব্যবহার করতে পারবেন না। আপনাকে স্পষ্টভাবে 'react' থেকে Fragment ইমপোর্ট করতে হবে এবং <Fragment key={yourKey}>...</Fragment> রেন্ডার করতে হবে।

  • যখন আপনি <><Child /></> থেকে [<Child />] রেন্ডারিং এ চলে যান বা ফিরে আসেন, অথবা <><Child /></> থেকে <Child /> রেন্ডারিং এ যান এবং ফিরে আসেন React state রিসেট করে না। এটা শুধুমাত্র এক স্তর গভীরে কাজ করেঃ উদাহরণস্বরূপ, <><><Child /></></> থেকে <Child /> এ গেলে state রিসেট হয়। সুনির্দিষ্ট semantics দেখুন এখানে।

  • If you want to pass ref to a Fragment, you can’t use the <>...</> syntax. You have to explicitly import Fragment from 'react' and render <Fragment ref={yourRef}>...</Fragment>.

FragmentInstance

When you pass a ref to a Fragment, React provides a FragmentInstance object. It implements methods for interacting with the first-level DOM children wrapped by the Fragment.


addEventListener(type, listener, options?)

Adds an event listener to all first-level DOM children of the Fragment.

fragmentRef.current.addEventListener('click', handleClick);
Parameters
  • type: A string representing the event type to listen for (e.g. 'click', 'focus').
  • listener: The event handler function.
  • optional options: An options object or boolean for capture, matching the DOM addEventListener API.
Returns

addEventListener does not return anything (undefined).


removeEventListener(type, listener, options?)

Removes an event listener from all first-level DOM children of the Fragment.

fragmentRef.current.removeEventListener('click', handleClick);
Parameters
  • type: The event type string.
  • listener: The event handler function to remove.
  • optional options: An options object or boolean, matching the DOM removeEventListener API.
Returns

removeEventListener does not return anything (undefined).


dispatchEvent(event)

Dispatches an event on the Fragment. Added event listeners are called, and the event can bubble to the Fragment’s DOM parent.

fragmentRef.current.dispatchEvent(new Event('custom', { bubbles: true }));
Parameters
  • event: An Event object to dispatch. If bubbles is true, the event bubbles to the Fragment’s parent DOM node.
Returns

true if the event was not cancelled, false if preventDefault() was called.


focus(options?)

Focuses the first focusable DOM node in the Fragment. Unlike calling element.focus() on a DOM element, this method searches all nested children depth-first until it finds a focusable element—not just the element itself or its direct children.

fragmentRef.current.focus();
Parameters
  • optional options: A FocusOptions object (e.g. { preventScroll: true }).
Returns

focus does not return anything (undefined).


focusLast(options?)

Focuses the last focusable DOM node in the Fragment. Searches nested children depth-first, then iterates in reverse.

fragmentRef.current.focusLast();
Parameters
Returns

focusLast does not return anything (undefined).


blur()

Removes focus from the active element if it is within the Fragment. If document.activeElement is not within the Fragment, blur does nothing.

fragmentRef.current.blur();
Returns

blur does not return anything (undefined).


observeUsing(observer)

Starts observing all first-level DOM children of the Fragment with the provided observer.

const observer = new IntersectionObserver(callback, options);
fragmentRef.current.observeUsing(observer);
Parameters
Returns

observeUsing does not return anything (undefined).


unobserveUsing(observer)

Stops observing the Fragment’s DOM children with the specified observer.

fragmentRef.current.unobserveUsing(observer);
Parameters
  • observer: The same IntersectionObserver or ResizeObserver instance previously passed to observeUsing.
Returns

unobserveUsing does not return anything (undefined).


getClientRects()

Returns a flat array of DOMRect objects representing the bounding rectangles of all first-level DOM children.

const rects = fragmentRef.current.getClientRects();
Returns

An Array<DOMRect> containing the bounding rectangles of all children.


getRootNode(options?)

Returns the root node containing the Fragment’s parent DOM node, matching the behavior of Node.getRootNode().

const root = fragmentRef.current.getRootNode();
Parameters
Returns

A Document, ShadowRoot, or the FragmentInstance itself if there is no parent DOM node.


compareDocumentPosition(otherNode)

Compares the document position of the Fragment with another node, returning a bitmask matching the behavior of Node.compareDocumentPosition().

const position = fragmentRef.current.compareDocumentPosition(otherElement);
Parameters
  • otherNode: The DOM node to compare against.
Returns

A bitmask of position flags. Empty Fragments and Fragments with children rendered through a portal include Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC in the result.


scrollIntoView(alignToTop?)

Scrolls the Fragment’s children into view. When alignToTop is true or omitted, scrolls to align the first child with the top of the scrollable ancestor. When alignToTop is false, scrolls to align the last child with the bottom.

fragmentRef.current.scrollIntoView();
Parameters
  • optional alignToTop: A boolean. If true (the default), scrolls the first child to the top of the scrollable area. If false, scrolls the last child to the bottom. Unlike Element.scrollIntoView(), this method does not accept a ScrollIntoViewOptions object.
Returns

scrollIntoView does not return anything (undefined).

Caveats
  • scrollIntoView does not accept an options object. Passing one throws an error. Use the alignToTop boolean instead.
  • When the Fragment has no children, scrollIntoView scrolls the nearest sibling or parent into view as a fallback.

FragmentInstance Caveats

  • Methods that target children (such as addEventListener, observeUsing, and getClientRects) operate on first-level host (DOM) children of the Fragment. They do not directly target children nested inside another DOM element.
  • focus and focusLast search nested children depth-first for focusable elements, unlike event and observer methods which only target first-level host children.
  • observeUsing does not work on text nodes. React logs a warning in development if the Fragment contains only text children.
  • React does not apply event listeners added via addEventListener to hidden <Activity> trees. When an Activity boundary switches from hidden to visible, listeners are applied automatically.
  • Each first-level DOM child of a Fragment with a ref gets a reactFragments property—a Set<FragmentInstance> containing all Fragment instances that own the element. This enables caching a shared observer across multiple Fragments.

ব্যবহার

একাধিক এলিমেন্ট রিটার্নিং

একাধিক এলিমেন্ট গ্রুপ করতে Fragment বা সমার্থক <>...</> সিনট্যাক্স ব্যবহার করুন। এমন যেকোন জায়গা যেখানে একটি এলিমেন্ট যেতে পারে সেখানে আপনি একাধিক এলিমেন্ট রাখার জন্য এটা ব্যবহার করতে পারেন। উদাহরণস্বরূপ, একটা কম্পোনেন্ট শুধুমাত্র একটি এলিমেন্ট রিটার্ন করতে পারে, কিন্তু ফ্র্যাগমেন্ট ব্যবহার করে আপনি একাধিক এলিমেন্টকে একসাথে করে গ্রুপ হিসেবে রিটার্ন করতে পারেনঃ

function Post() {
return (
<>
<PostTitle />
<PostBody />
</>
);
}

ফ্র্যাগমেন্ট কাজে লাগে কারণ ফ্র্যাগমেন্টে এলিমেন্ট গ্রুপ করলে সেটা লেআউট বা স্টাইলে কোন প্রভাব ফেলে না, যে সুবিধাটা আপনি DOM এলিমেন্টের মত অন্য একটা কনটেইনারে এলিমেন্টগুলো wrap করলে পেতেন না। আপনি যদি ব্রাউজার টুল ব্যবহার করে এই উদাহরণটি inspect করেন, দেখবেন যে সব <h1> এবং <article> DOM নোডকে sibling হিসেবে দেখায়। তাদের ঘিরে কোন wrapper দেখবেন নাঃ

export default function Blog() {
  return (
    <>
      <Post title="An update" body="It's been a while since I posted..." />
      <Post title="My new blog" body="I am starting a new blog!" />
    </>
  )
}

function Post({ title, body }) {
  return (
    <>
      <PostTitle title={title} />
      <PostBody body={body} />
    </>
  );
}

function PostTitle({ title }) {
  return <h1>{title}</h1>
}

function PostBody({ body }) {
  return (
    <article>
      <p>{body}</p>
    </article>
  );
}

গভীরভাবে জানুন

বিশেষ সিনট্যাক্স ব্যবহার না করে কীভাবে একটি ফ্র্যাগমেন্ট লিখতে হয়?

উপরের এই উদাহরণটি React থেকে Fragment ইমপোর্ট করার মতই কাজ করবেঃ

import { Fragment } from 'react';

function Post() {
return (
<Fragment>
<PostTitle />
<PostBody />
</Fragment>
);
}

সাধারণত আপনার এর দরকার পড়বে না যদি না আপনার Fragment এ একটা key পাস করার প্রয়োজন পড়ে।


একটি ভ্যারিয়েবলে একাধিক এলিমেন্ট এসাইনিং

অন্য যেকোন এলিমেন্টের মত, আপনি ফ্র্যাগমেন্ট এলিমেন্ট ভ্যারিয়েবলে এসাইন করতে পারবেন, prop হিসেবে পাস করতে পারবেন, এবং আরো যা যা করা যায় করতে পারবেনঃ

function CloseDialog() {
const buttons = (
<>
<OKButton />
<CancelButton />
</>
);
return (
<AlertDialog buttons={buttons}>
Are you sure you want to leave this page?
</AlertDialog>
);
}

টেক্সটের সাথে এলিমেন্ট এর গ্রুপিং

আপনি কম্পোনেন্টের সাথে টেক্সট গ্রুপ করতে চাইলে Fragment ব্যবহার করতে পারেনঃ

function DateRangePicker({ start, end }) {
return (
<>
From
<DatePicker date={start} />
to
<DatePicker date={end} />
</>
);
}

ফ্র্যাগমেন্টের একটা তালিকার রেন্ডার

এখানে এমন একটা অবস্থা দেখা যাচ্ছে যেখানে আপনাকে <></> এর জায়গায় স্পষ্টভাবে Fragment সিনট্যাক্স ব্যবহার করতে হবে। যখন আপনি একটা লুপে একাধিক এলিমেন্ট রেন্ডার করছেন, আপনাকে প্রতি এলিমেন্টের জন্য একটি key ঠিক করে দিতে হবে। যদি লুপের মধ্যকার এলিমেন্টগুলা ফ্র্যাগমেন্ট হয়, আপনাকে key এট্রিবিউট দেবার জন্য সাধারণ JSX এলিমেন্ট সিনট্যাক্স ব্যবহার করতে হবেঃ

function Blog() {
return posts.map(post =>
<Fragment key={post.id}>
<PostTitle title={post.title} />
<PostBody body={post.body} />
</Fragment>
);
}

আপনি DOM এ inspect করে দেখতে পারেন ফ্র্যাগমেন্ট চিলড্রেন এর আসে পাশে কোন wrapper এলিমেন্ট নেইঃ

import { Fragment } from 'react';

const posts = [
  { id: 1, title: 'An update', body: "It's been a while since I posted..." },
  { id: 2, title: 'My new blog', body: 'I am starting a new blog!' }
];

export default function Blog() {
  return posts.map(post =>
    <Fragment key={post.id}>
      <PostTitle title={post.title} />
      <PostBody body={post.body} />
    </Fragment>
  );
}

function PostTitle({ title }) {
  return <h1>{title}</h1>
}

function PostBody({ body }) {
  return (
    <article>
      <p>{body}</p>
    </article>
  );
}


Adding event listeners without a wrapper element

Fragment refs let you add event listeners to a group of elements without adding a wrapper DOM node. Use a ref callback to attach and clean up listeners:

import { Fragment, useState, useRef, useEffect } from 'react';

function ClickableFragment({ children, onClick }) {
  const fragmentRef = useRef(null);
  useEffect(() => {
    const fragmentInstance = fragmentRef.current;
    if (fragmentInstance === null) {
      return;
    }
    fragmentInstance.addEventListener('click', onClick);
    return () => {
      fragmentInstance.removeEventListener(
        'click',
        onClick
      );
    };
  }, [onClick])
  return (
    <Fragment ref={fragmentRef}>
      {children}
    </Fragment>
  );
}

export default function App() {
  const [clicks, setClicks] = useState(0);

  return (
    <>
      <p>Total clicks: {clicks}</p>
      <ClickableFragment onClick={() => {
        setClicks(c => c + 1);
      }}>
        <button>Button A</button>
        <button>Button B</button>
        <button>Button C</button>
      </ClickableFragment>
    </>
  );
}

The addEventListener call applies the listener to every first-level DOM child of the Fragment. When children are dynamically added or removed, the FragmentInstance automatically adds or removes the listener.

গভীরভাবে জানুন

Which children does a Fragment ref target?

A FragmentInstance targets the first-level host (DOM) children of the Fragment. Consider this tree:

<Fragment ref={ref}>
<div id="A" />
<Wrapper>
<div id="B">
<div id="C" />
</div>
</Wrapper>
<div id="D" />
</Fragment>

Wrapper is a React component, so the FragmentInstance looks through it to find DOM nodes. The targeted children are A, B, and D. C is not targeted because it is nested inside the DOM element B.

Methods like addEventListener, observeUsing, and getClientRects operate on these first-level DOM children. focus and focusLast are different—they search all nested children depth-first to find focusable elements.


Managing focus across a group of elements

Fragment refs provide focus, focusLast, and blur methods that operate across all DOM nodes within the Fragment:

import { Fragment, useRef } from 'react';

function FormFields({ children }) {
  const fragmentRef = useRef(null);

  return (
    <>
      <div className="buttons">
        <button onClick={() => {
          fragmentRef.current.focus();
        }}>
          Focus first
        </button>
        <button onClick={() => {
          fragmentRef.current.focusLast();
        }}>
          Focus last
        </button>
        <button onClick={() => {
          fragmentRef.current.blur();
        }}>
          Blur
        </button>
      </div>
      <Fragment ref={fragmentRef}>
        {children}
      </Fragment>
    </>
  );
}

// Even though the inputs are deeply nested,
// focus() searches depth-first to find them.
export default function App() {
  return (
    <FormFields>
      <fieldset>
        <legend>Shipping</legend>
        <label>
          Street: <input name="street" />
        </label>
        <label>
          City: <input name="city" />
        </label>
      </fieldset>
    </FormFields>
  );
}

Calling focus() focuses the street input—even though it is nested inside a <fieldset> and <label>. focus() searches depth-first through all nested children, not just direct children of the Fragment. focusLast() does the same in reverse, and blur() removes focus if the currently focused element is within the Fragment.


Scrolling a group of elements into view

Use scrollIntoView to scroll a Fragment’s children into view without a wrapper element. Pass true (or omit the argument) to scroll the first child to the top. Pass false to scroll the last child to the bottom:

import { Fragment, useRef } from 'react';

function ScrollableSection({ children }) {
  const fragmentRef = useRef(null);

  return (
    <>
      <div className="buttons">
        <button onClick={() => {
          fragmentRef.current.scrollIntoView();
        }}>
          Scroll to top
        </button>
        <button onClick={() => {
          fragmentRef.current.scrollIntoView(false);
        }}>
          Scroll to bottom
        </button>
      </div>
      <div className="container">
        <Fragment ref={fragmentRef}>
          {children}
        </Fragment>
      </div>
    </>
  );
}

const items = [];
for (let i = 1; i <= 25; i++) {
  items.push('Item ' + i);
}

export default function App() {
  return (
    <ScrollableSection>
      <h3>Section Start</h3>
      {items.map((item) => (
        <p key={item}>{item}</p>
      ))}
      <h3>Section End</h3>
    </ScrollableSection>
  );
}


Observing visibility without a wrapper element

Use observeUsing to attach an IntersectionObserver to all first-level DOM children of a Fragment. This lets you track visibility without requiring child components to expose refs or adding a wrapper element:

import {
  Fragment,
  useRef,
  useLayoutEffect,
  useState,
} from 'react';
import Card from './Card';

function VisibleGroup({ onVisibilityChange, children }) {
  const fragmentRef = useRef(null);

  useLayoutEffect(() => {
    const visibleElements = new Set();
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach(e => {
          if (e.isIntersecting) {
            visibleElements.add(e.target);
          } else {
            visibleElements.delete(e.target);
          }
        });
        onVisibilityChange(visibleElements.size > 0);
      }
    );
    const fragmentInstance = fragmentRef.current;
    fragmentInstance.observeUsing(observer);
    return () => {
      fragmentInstance.unobserveUsing(observer);
    };
  }, [onVisibilityChange]);

  return (
    <Fragment ref={fragmentRef}>
      {children}
    </Fragment>
  );
}

export default function App() {
  const [isVisible, setIsVisible] = useState(true);

  return (
    <div className={isVisible ? 'page visible' : 'page'}>
      <div className="filler">Scroll down</div>
      <VisibleGroup onVisibilityChange={setIsVisible}>
        <Card title="First section" />
        <Card title="Second section" />
      </VisibleGroup>
      <div className="filler">Scroll up</div>
    </div>
  );
}


Caching a global IntersectionObserver

A common performance optimization for sites with many observers is to share a single IntersectionObserver per config and route its entries to the correct callbacks based on which element intersected. Fragment refs support this same pattern through the reactFragments property.

Each first-level DOM child of a Fragment with a ref has a reactFragments property: a Set of FragmentInstance objects that contain that element. When the shared observer fires, you can use this property to look up which FragmentInstance owns the intersecting element and run the right callbacks.

import { useState, useCallback } from 'react';
import ObservedGroup from './ObservedGroup';
import Card from './Card';

export default function App() {
  const [bgColor, setBgColor] = useState(null);

  const onGreen = useCallback((entry) => {
    if (entry.isIntersecting) {
      setBgColor('#d4edda');
    }
  }, []);

  const onBlue = useCallback((entry) => {
    if (entry.isIntersecting) {
      setBgColor('#cce5ff');
    }
  }, []);

  return (
    <div className="page" style={{
      background: bgColor || 'white',
    }}>
      <div className="filler">Scroll down</div>
      <ObservedGroup onIntersection={onGreen}>
        <Card title="Green section" className="green" />
      </ObservedGroup>
      <div className="filler" />
      <ObservedGroup onIntersection={onBlue}>
        <Card title="Blue section" className="blue" />
      </ObservedGroup>
      <div className="filler">Scroll up</div>
    </div>
  );
}

Multiple ObservedGroup components with the same options reuse a single IntersectionObserver. When either section scrolls into view, the shared observer fires and uses reactFragments to route the entry to the correct callback.