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

<Fragment>, genellikle <>...</> syntax’ı ile kullanılır ve element’leri bir wrapper node olmadan gruplamanızı sağlar.

Test Ortamı (Canary)

Fragment’lar ayrıca ref kabul edebilir; bu da wrapper element eklemeden underlying DOM node’larıyla etkileşim kurmayı sağlar.
<>
<AltEleman />
<BaskaAltEleman />
</>

Referans

<Fragment>

Tek bir elemana ihtiyaç duyduğunuz durumlarda, elemanları <Fragment> içine alarak onları bir araya getirebilirsiniz. Fragment içinde elemanları gruplamak, sonuç DOM üzerinde herhangi bir etkiye sahip değildir; sanki elemanlar gruplanmamış gibi aynı kalır. Boş JSX etiketi <></> çoğu durumda <Fragment></Fragment> için kısaltmadır.

Prop’lar

  • optional key: Açık <Fragment> syntax’iyle tanımlanan Fragment’lar key’lere sahip olabilir.
  • Canary only optional ref: Bir ref object’i (örn. useRef’ten gelen) veya callback function. React, ref value olarak Fragment tarafından sarılan DOM node’larıyla etkileşim kurmak için method’lar implemente eden bir FragmentInstance sağlar.

Uyarılar

  • Bir Fragment’a key geçirmek istiyorsanız, <>...</> syntax’ini kullanamazsınız. 'react' içinden Fragment’ı açıkça import etmeniz ve <Fragment key={yourKey}>...</Fragment> şeklinde render etmeniz gerekir.

  • React, <><Child /></> render etmekten [<Child />] render etmeye geçtiğinizde veya geri döndüğünüzde ya da <><Child /></> render etmekten <Child /> render etmeye geçtiğinizde ve geri döndüğünüzde state’i resetlemez. Bu yalnızca tek bir seviye derinlikte çalışır: örneğin, <><><Child /></></> yapısından <Child /> yapısına geçmek state’i resetler. Kesin semantiklere buradan bakabilirsiniz.

  • Canary only Bir Fragment’a ref geçirmek istiyorsanız, <>...</> syntax’ini kullanamazsınız. 'react' içinden Fragment’ı açıkça import etmeniz ve render etmeniz gerekir<Fragment ref={yourRef}>...</Fragment>.


Canary only FragmentInstance

Bir Fragment’a ref geçirdiğinizde, React bir FragmentInstance object’i sağlar. Bu object, Fragment tarafından sarılan birinci seviye DOM child’larıyla etkileşim kurmak için method’lar implemente eder.

  • addEventListener ve removeEventListener, tüm birinci seviye DOM child’ları üzerinde event listener’ları yönetir.
  • dispatchEvent, Fragment üzerinde bir event dispatch eder; bu event DOM parent’a bubble olabilir.
  • focus, focusLast ve blur, tüm nested child’lar üzerinde depth-first şekilde focus’u yönetir.
  • observeUsing ve unobserveUsing, IntersectionObserver veya ResizeObserver instance’larını attach ve detach eder.
  • getClientRects, tüm birinci seviye DOM child’larının bounding rectangle’larını döndürür.
  • getRootNode, Fragment’ın parent’ının root node’unu döndürür.
  • compareDocumentPosition, Fragment’ın konumunu başka bir node ile karşılaştırır.
  • scrollIntoView, Fragment’ın child’larını görünüme kaydırır.

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.

Kullanım

Birden Fazla Eleman Döndürme

Fragment veya, <>...</> sözdizimini kullanmak birden fazla elemanı bir araya getirir. Tek bir elemanın gidebileceği herhangi bir yere birden fazla eleman koymak için kullanabilirsiniz. Örneğin, bir bileşen sadece bir eleman döndürebilir, ancak Fragment kullanarak birden fazla elemanı bir araya getirebilir ve onları bir grup olarak döndürebilirsiniz:

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

Fragmanlar kullanışlıdır çünkü bir Fragment ile elemanları gruplamak, elemanları bir DOM elemanı gibi başka bir konteynerde sarmak gibi düzeni veya stilleri etkilemez. Tarayıcı araçlarıyla bu örneği incelediğinizde, tüm <h1> ve <p> DOM düğümlerinin etrafında sarmalayıcı olmadan kardeşler olarak görünecektir.

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>
  );
}

Derinlemesine İnceleme

Özel sözdizimi olmadan bir Fragment nasıl yazılır?

Yukarıdaki örnek, React’ten Fragment içe aktarmaya eşdeğerdir:

import { Fragment } from 'react';

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

Genellikle bunun gibi bir şeye ihtiyaç duymazsınız, ancak [Fragment’a key eklemek] istediğinizde kullanabilirsiniz.(#rendering-a-list-of-fragments)


Bir değişkene birden fazla eleman atama

Diğer tüm elemanlar gibi, Fragment elemanlarını değişkenlere atayabilir, bunları props olarak iletebilir ve benzeri işlemler yapabilirsiniz:

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

Metinle elemanları gruplama

Fragment ile, metni bileşenlerle bir araya getirmek için kullanabilirsiniz:

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

Fragment’lar listesini oluşturma:

İşte <></> sözdizimini yerine Fragment yazmanız gereken bir durum. Bir döngüde birden fazla elemanı oluşturduğunuzda, her elemana bir key atamanız gerekmektedir. Eğer döngü içindeki elemanlar Fragment ise, key özelliğini sağlamak için normal JSX eleman sözdizimini kullanmanız gerekir:

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

DOM’u, Fragment alt elemanlarının etrafında sarmalayıcı öğe olmadığını doğrulamak için inceleyebilirsiniz:

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>
  );
}


Canary only Wrapper element olmadan event listener ekleme

Fragment refleri, wrapper DOM node’u eklemeden bir grup elemente event listener eklemenizi sağlar. Listener’ları attach etmek ve cleanup yapmak için bir ref callback kullanın:

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.

Derinlemesine İnceleme

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.


Canary only Bir grup element üzerinde focus yönetme

Fragment refleri, Fragment içindeki tüm DOM node’ları üzerinde çalışan focus, focusLast ve blur method’larını sağlar:

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.


Canary only 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>
  );
}


Canary only 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>
  );
}


Canary only 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.