What's the difference between import React from 'react'
and import React { Fragment } from 'react'
in context of <React.Fragment>
, <Fragment>
and <>
?
I mean what happen when we import React
and { Fragment }
in the same line from a module?
Do we create instance of <Fragment>
and this is just another few hundreds lines of code under the hood?
Or this is just normal and everybody can do that withouth performance downsides?
Official React blogpost mention that you can do this const Fragment = React.Fragment
and they use in in their examples.
But why?
<> is the shorthand tag for React. Fragment which allows us to group a list of elements without wrapping them in a new node. The only difference between them is that the shorthand version does not support the key attribute.
The main difference between React. Fragment vs div is that using a React. Fragment will not add any additional elements into the DOM tree, whereas, using a div will add a div to the DOM tree.
React Fragments allow you to wrap or group multiple elements without adding an extra node to the DOM. This can be useful when rendering multiple child elements/components in a single parent component.
Therefore, React fragments are better than the 'div' tags. With React Fragment, you can render multiple elements of a component without adding extra div tags. We can write cleaner, more readable code with React Fragments. It takes up less memory and renders components faster. Each component is rendered as expected.
So assume you have an object.
let object = {
foo: '1',
bar: '2',
};
In order to use the value foo
you can do the following
object.foo
let { foo } = object
These both are the same, the later mentioned way is called destructing which was introduced in javascript ES6 version.
Now coming to topic for
What's the difference between import React from 'react' and import React { Fragment } from 'react' in context of , and <>?
imagine React
as object which has the following features e.g Fragment
in this case. You can access it the following ways
1- First way
import React from 'react';
<React.Fragment></React.Fragment>
2-
import React, { Fragment } from 'react';
<Fragment></Fragment>
Now in the second way this is basically importing all React features and also destructing a feature from React
which is Fragment
. SO you don't have to write React.Fragment
again and again.
3-
<></>
This is a babel feature, babel when compiling will convert <></>
this into <React.Fragment></React.Fragment>
<></>
syntax doesn’t support keys or attributes. When element is iterated it will throw the warning message 'Each child in a list should have a unique "key" prop'.
For Example :
{props.items.map(item => (
<>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</>
))}
See docs here https://reactjs.org/docs/fragments.html#keyed-fragments
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With