3

I was looking through a .tsx code that looked something like below.

import React, { Fragment, ReactFragment } from "react";

// ...
export interface PageProps {
   children: ReactFragment;
   commandBar: reactFragment;
   // ...
}
    
export default page(props: PageProps) {
   return(
      <Fragment>
        // ...
      </Fragment>
   );
}

I roughly know what a React.Fragment is.
We can use either <></> or <React.Fragment></React.Fragment> or <Fragment></Fragment> based on the import sugaring, to group react elements.

So, my question is how does ReactFragment work here?
Is it just to indicate that children or commandBar is of a React.Fragment type?

In that case, why not use React.Fragment itself? Googling throwed results for React.Fragment only.

NIV
  • 458
  • 4
  • 19
  • I haven't found ReactFragment from "react". https://github.com/facebook/react/tree/master/packages/react/src – Ravi Garg Aug 10 '20 at 08:53
  • 1
    @spycbanda Because it is not part of React. https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L238 – zmag Aug 10 '20 at 09:08

3 Answers3

2

Is it just to indicate that children or commandBar is of a React.Fragment type?

Yes.

In that case, why not use React.Fragment itself?

React.Fragment is not a type but a value. If you used it, you will see an compile error like this:

'Fragment' refers to a value, but is being used as a type here.
zmag
  • 7,825
  • 12
  • 32
  • 42
1

See the below screenshot.

enter image description here

ReactFragment is one of the valid values for ReactNode which intern can be Array<ReactNode> so you can have a valid return as ReactFragment i.e. <></> or <React.Fragment></React.Fragment> for your component.

import React, { ReactFragment } from 'react';

function MyComp(): ReactFragment {
    //it can return any of boolean, null, undefined, ReactChild, ReactFragment
    return (
        <></> 
    )
}

Here we specifically define the type to be a ReactFragment. Even if you return boolean, null, undefined, ReactChild, ReactFragment it will accept as it extends Array<ReactNode>.

In nutshell ReactFragment is a type that a component can return.

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L238

Pramod Mali
  • 1,588
  • 1
  • 17
  • 29
  • The question is over ReactFragment and not React.Fragment. Read the question clearly. – Ravi Garg Aug 10 '20 at 08:52
  • Thanks for that! But that is all about React.Fragment and I have mentioned that I knew that concept. How do I relate your anwser to ReactFragment? – NIV Aug 10 '20 at 08:53
1

ReactFragment is a type (e.g. ReactNode can also be a ReactFragment) where Fragment is the pattern in react that lets you return grouped children.

Ioannis Potouridis
  • 1,246
  • 6
  • 7