ReactJS Tutorial - 25 - Fragments

Codevolution
2 Jan 201909:42

Summary

TLDRThis video tutorial delves into React Fragments, a feature that allows developers to group child elements without adding extra nodes to the DOM. The instructor begins by creating a 'Fragment Demo' component, illustrating how fragments solve the issue of JSX requiring a single parent element for multiple children. They demonstrate the use of fragments in a table example, showing how fragments can eliminate unwanted div tags and resolve console warnings about improper DOM nesting. The video also covers the key attribute in fragments for rendering lists and the shorthand syntax for fragments, highlighting its limitation of not allowing key attributes. The tutorial is a practical guide for React developers looking to streamline their JSX structures.

Takeaways

  • 📕 React Fragments are used to group a list of children elements without adding extra nodes to the DOM.
  • 📝 In React, when returning multiple elements, they must be enclosed within a single parent element.
  • 📝 The error message 'JSX expressions must have one parent element' indicates that JSX elements need to be wrapped in an enclosing tag.
  • 📝 React Fragments can prevent the addition of unnecessary DOM nodes by replacing enclosing tags like div.
  • 📝 The DOM tree can be cleaned up by using React Fragments, as they do not add extra nodes like divs.
  • 📝 React Fragments can be used in scenarios where multiple elements are returned, such as in table rows with multiple cells.
  • 📝 Console warnings like 'validate DOM nesting TD cannot appear as a child of the div' can be resolved by using React Fragments.
  • 📝 The key attribute can be passed to React Fragments when rendering lists of items, which is useful for identifying elements in a collection.
  • 📝 Currently, the key attribute is the only attribute that can be passed to a React Fragment, with potential for more attributes to be supported in the future.
  • 📝 There is a shorthand syntax for React Fragments using empty opening and closing tags, but this does not support passing the key attribute.

Q & A

  • What is the primary purpose of React Fragments?

    -React Fragments allow you to group a list of children elements without adding extra nodes to the DOM.

  • How do you create a React Fragment?

    -You can create a React Fragment by using either `<React.Fragment>` or the shorthand syntax `<>...</>`.

  • What is the issue when returning multiple JSX elements without using a Fragment?

    -If you return multiple JSX elements without using a Fragment, React will throw an error stating that JSX expressions must have one parent element.

  • Why is it important to avoid extra nodes in the DOM?

    -Avoiding extra nodes in the DOM is important for performance optimization and to prevent unnecessary nesting that can lead to styling and layout issues.

  • Can you pass the 'key' attribute to a React Fragment?

    -Yes, you can pass the 'key' attribute to a React Fragment, which is especially useful when rendering lists of items.

  • What is the limitation of using the shorthand syntax for React Fragments?

    -The limitation of using the shorthand syntax for React Fragments is that you cannot pass in the 'key' attribute.

  • How do you fix the warning 'validateDOMNesting TD cannot appear as a child of a div'?

    -You can fix this warning by replacing the enclosing `div` tag with a `<React.Fragment>` to prevent the extra node from being added to the DOM.

  • What is the correct way to include a React Fragment in a component?

    -You include a React Fragment in a component by replacing the enclosing parent tag (like `div`) with `<React.Fragment>` or `<>...</>`.

  • What is the significance of the 'key' attribute in the context of React Fragments?

    -The 'key' attribute is significant in React Fragments when rendering lists as it helps React identify which items have changed, are added, or are removed, which is crucial for performance optimization.

  • Can React Fragments accept attributes other than 'key'?

    -As of the knowledge cutoff in 2023, React Fragments can only accept the 'key' attribute. However, React plans to allow additional attributes in the future.

  • What is the benefit of using React Fragments over a simple enclosing tag like 'div'?

    -Using React Fragments over a simple enclosing tag like 'div' prevents the addition of unnecessary DOM elements, which can lead to cleaner HTML structure, better performance, and fewer potential layout issues.

Outlines

00:00

🛠️ Introduction to React Fragments

This paragraph introduces React fragments, explaining their purpose and functionality. A React fragment allows developers to group a list of child elements without adding extra nodes to the Document Object Model (DOM). The tutorial begins by creating a new file named 'fragment demo.js' and using a React snippet to create a functional component. The component is then added to the 'app' component. The instructor then demonstrates how to convert text into a heading using an 'h1' tag and add a description using a 'p' tag. However, this results in a JSX error because JSX expressions must have one parent element. To fix this, an enclosing 'div' tag is added. Upon saving the changes, the application works, but an extra 'div' tag is added to the DOM. To avoid this, React fragments are used in place of the 'div' tag, which prevents the extra node from being added to the DOM. The paragraph concludes with another example where fragments are more appropriate, such as creating a table with columns in separate components.

05:03

📚 Advanced Usage of React Fragments

The second paragraph delves into more advanced usage of React fragments, focusing on DOM nesting validation and the shorthand syntax for fragments. The instructor creates two new files, 'table.js' and 'columns.js', to demonstrate how to create a table with columns. Initially, an enclosing 'div' tag is used to return multiple elements, which leads to console warnings about incorrect DOM nesting. The 'div' tag is then replaced with a React fragment to resolve these warnings. The paragraph also discusses the ability of fragments to accept the 'key' attribute when rendering lists, which is crucial for performance optimization in React. The instructor provides an example of how to use fragments with the 'key' attribute and mentions that React plans to support additional attributes for fragments in the future. The paragraph concludes with a discussion of the shorthand syntax for fragments, which allows for the grouping of elements without adding extra nodes to the DOM, but notes that the shorthand syntax does not support the 'key' attribute.

Mindmap

Keywords

💡React

React is a popular JavaScript library for building user interfaces, particularly single-page applications. It allows developers to create and manage views in a more efficient way by using components. In the video, React serves as the foundation for discussing advanced topics such as fragments.

💡Fragments

React Fragments are a feature that allows developers to group a list of child elements together without adding extra nodes to the DOM. This is crucial for preventing unwanted HTML elements from being rendered. In the script, fragments are used to return multiple elements in a component without creating an additional wrapping div.

💡JSX

JSX is a syntax extension for JavaScript that allows developers to write HTML-like structures in their JavaScript code. It is used in React to describe the UI and its current state. The video script mentions JSX expressions and how they must have one parent element, which is resolved using fragments.

💡Functional Component

A functional component in React is a component that is defined as a JavaScript function. It receives props as its argument and returns a React element. The script uses functional components to demonstrate how fragments can be used to group elements without adding extra nodes to the DOM.

💡DOM

DOM stands for Document Object Model, which is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML, and XML documents. The video discusses how React fragments prevent extra nodes from being added to the DOM, thus maintaining a clean structure.

💡Enclosing Tag

In the context of JSX, an enclosing tag is a parent element that wraps multiple child elements. The video explains that when returning multiple elements in a component, they must be enclosed within a single parent element to avoid errors.

💡Key Attribute

The key attribute in React is used to help React identify which items have changed, are added, or are removed when rendering lists of elements. It is the only attribute that can be passed to a React fragment, as mentioned in the video, to ensure that each element in a list can be uniquely identified.

💡Shorthand Syntax

Shorthand syntax for React fragments allows developers to group child elements without explicitly writing the React fragment component. Instead, an empty opening and closing tag is used. This is demonstrated in the script as a more concise way to use fragments.

💡Table Component

In the script, a table component is created to demonstrate how fragments can be used in more complex structures like tables. It uses a table tag and includes a tbody and tr tag to create a row of data, which is then filled with columns using another component.

💡Columns Component

The columns component is a separate component used within the table component to manage the individual columns of data. It illustrates how fragments can be used to return multiple elements like TD tags without wrapping them in an extra div, which would cause DOM nesting issues.

💡Warnings

Warnings in the console are messages that alert developers to potential issues in their code. In the video, warnings about invalid DOM nesting are resolved by using React fragments to correctly structure the elements within the table and columns components.

Highlights

Introduction to React fragments and their purpose in grouping child elements without adding extra nodes to the DOM.

Creating a new file 'fragment demo.js' to demonstrate React fragments.

Using the React snippet 'rfc' to create a functional component.

Incorporating the fragment demo component into the app component.

Adding a heading and a paragraph to the fragment demo component.

Encountering the error that JSX expressions must have one parent element.

Solving the error by enclosing multiple elements within a single parent element.

Inspecting the DOM to understand the impact of enclosing tags on the DOM tree.

Using React fragments to prevent the addition of extra nodes to the DOM.

Replacing the enclosing div tag with React fragment in the fragment demo component.

Demonstrating the correct rendering in the browser without extra DOM nodes.

Creating a table component and a columns component to showcase React fragments in a table structure.

Addressing console warnings about invalid DOM nesting by using React fragments.

Using React fragments to eliminate console warnings and improve DOM structure.

Explaining that React fragments can accept the key attribute for rendering lists.

Providing an example of using the key attribute with React fragments for list rendering.

Introducing the shorthand syntax for React fragments using empty tags.

Discussing the limitation of the shorthand syntax regarding the key attribute.

Concluding the video with a summary of React fragments' functionality and benefits.

Transcripts

play00:00

alright guys now that we have the basics

play00:02

of react behind us it's time to focus on

play00:05

some of the topics mentioned under the

play00:08

Advanced section in the official react

play00:11

documentation let's start with one of

play00:14

the more easier topics to understand in

play00:16

this video let's learn about react

play00:19

fragments fragments basically lets you

play00:23

group a list of children elements

play00:25

without adding extra nodes to the Dom

play00:28

let us understand what that means with

play00:31

an example vs code and we'll start off

play00:35

by creating a new file fragment demo dot

play00:38

jeaious

play00:44

within the file I'm going to use the

play00:46

reactor snippet RFC II to create a

play00:49

functional component

play00:52

in the JSX I will simply specify the

play00:54

text fragment demo in the app component

play00:59

I will include the fragment demo

play01:01

component

play01:06

if you save the files and take a look at

play01:08

the browser you should be able to see

play01:10

the text fragment demo now let's go back

play01:14

to the fragment demo component and add a

play01:16

few more elements in the JSX now I want

play01:20

to convert the text fragment demo into a

play01:23

heading so I will replace the div tag

play01:25

with an h1 tag

play01:32

right after the heading I want to add a

play01:35

simple description using a paragraph tag

play01:38

this describes the fragment demo

play01:42

component

play01:45

but when I do this we get a red squiggly

play01:48

line at the closing parenthesis of the

play01:51

return statement and when I hover on

play01:53

that you can see that it says JSX

play01:56

expressions must have one parent element

play02:00

if you save the file and take a look at

play02:02

the browser you can see that the

play02:04

application is broken as well and the

play02:07

error message points to the same thing

play02:10

adjacent JSX elements must be wrapped in

play02:13

an enclosing tag so anytime your

play02:17

component has to return multiple

play02:20

elements you have to enclose them in a

play02:23

single parent element so let's add that

play02:26

in closing div tag

play02:32

when I format it you can see that we

play02:34

have an enclosing dip tag and the each

play02:36

one and the paragraph elements are

play02:38

contained within this enclosing div tag

play02:41

if you now save the file and take a look

play02:44

at the browser everything works fine but

play02:48

if we inspect the element you can notice

play02:50

that we have the enclosing div tag

play02:53

included in the Dom tree so between the

play02:57

div tag from app component and the h1

play03:00

tag in fragment demo component we have

play03:03

an additional div tag this is well react

play03:07

fragments come into picture we can

play03:11

replace the enclosing div tag with react

play03:14

fragment and that will prevent the extra

play03:17

node from being added to the Dom so all

play03:21

you have to do is in fragment demo

play03:23

component replace this existing div tag

play03:26

with react dot fragment

play03:34

make sure to change the closing tag as

play03:36

well now if you save the file and go

play03:40

back to the browser inspect the element

play03:43

you can see that we no longer have the

play03:46

div tag between the app component div

play03:49

tag and the h1 tag and if you go back to

play03:53

vs code you can see that we are still

play03:56

returning multiple elements in the JSX

play03:59

all right now let's take a look at

play04:02

another example where react fragments

play04:05

seems much more appropriate I am going

play04:09

to create two new files so within the

play04:11

components folder table dot j s and

play04:19

columns dot j s within the table file

play04:24

i'm going to use the react snippet r f

play04:27

c/e to create a functional component for

play04:31

the GS x i'm going to replace the div

play04:33

tag with a table tag and within the

play04:38

table I'm going to add a tee body tag

play04:42

and then a TR tag to create a row of

play04:46

data within the row I want to render

play04:50

columns and the columns will be

play04:53

maintained in a separate component which

play04:56

is our columns component so let's go to

play04:59

column Jes and using the reacts Tibet

play05:02

our FCE create another functional

play05:05

component within the JSX I'm going to

play05:09

add two columns so TD name and another

play05:14

TD which was because we are returning

play05:19

multiple elements we need the enclosing

play05:21

div tag now back in the table component

play05:25

I will include the columns component

play05:30

and back in app component I will include

play05:34

the table component

play05:41

if you know save all the files and take

play05:44

a look at the browser you should be able

play05:46

to see the two columns name and vishwas

play05:49

if you take a look at the console though

play05:52

we have warnings and the warning is

play05:56

validate Dom nesting TD cannot appear as

play06:00

a child of the dev had basically it is

play06:04

telling us that it is wrong to have a TD

play06:07

element as a child of a div tag if I

play06:12

inspect the element

play06:16

you can pretty much see that in the dom

play06:18

tree pd within the div tag and this dip

play06:23

tag was necessary because we were

play06:25

returning multiple elements in the JSX

play06:28

of columns component but hey now we have

play06:32

the better alternative we can replace

play06:35

this div tag with react dot fragment so

play06:40

I'm going to go back to vs code and in

play06:42

columns component I'm going to replace

play06:45

the div tag with react dot fragment

play06:50

if you now go back to the browser you

play06:53

can see that all console warnings have

play06:56

disappeared if we inspect the element

play07:01

you can see that we have the table tag

play07:04

tbody

play07:05

TR and then TD there is no div tag in

play07:09

between the final point on fragments is

play07:14

that it can accept the key attribute

play07:16

when rendering lists of items for

play07:21

example let's assume we have an array of

play07:23

items stored in a variable called items

play07:27

then we could have items dot map and

play07:32

then we have an arrow function the

play07:34

parameter is item

play07:40

and the function can return a react

play07:43

fragment because items in the list need

play07:47

the key prop though we can specify the

play07:49

key attribute on react fragment key is

play07:53

equal to let's say item dot ID

play07:57

and within the JSX we can have multiple

play08:00

elements being returned let's say a

play08:03

heading that says title and then a

play08:07

paragraph tag that renders

play08:13

item dot title this is completely

play08:18

possible as of this recording key

play08:22

attribute is the only attribute that can

play08:25

be passed to a reactive fragment the

play08:28

reactive hopes to add additional

play08:29

attributes in the future but for now

play08:31

keep in mind to pass in only the key

play08:35

attribute

play08:36

now there is also a shorthand syntax

play08:39

that you can use for react fragments

play08:42

instead of react dot fragment you can

play08:45

use an empty opening tag and an empty

play08:47

closing tag I will get rid of this items

play08:51

rendering and now I can replace react

play08:55

dot fragment with an empty opening tag

play08:58

and an empty closing tag this basically

play09:02

represents the idea that it won't add an

play09:05

actual element to the Dom if you do use

play09:09

this shorthand syntax though there is

play09:12

one limitation you cannot pass in the

play09:16

key attribute so let's save this and

play09:19

take a look at the browser and you

play09:21

should still see name and which was the

play09:24

two columns we have specified so that is

play09:28

about react fragments fragments let you

play09:31

group a list of children elements

play09:33

without adding extra nodes to the Dom

play09:36

thank you guys for watching don't forget

play09:39

subscribe I'll see you guys in the next

play09:40

video

Rate This

5.0 / 5 (0 votes)

Ähnliche Tags
ReactJSFragmentsDOMWeb DevelopmentJavaScriptTutorialFunctional ComponentsJSXCodingWeb Components
Benötigen Sie eine Zusammenfassung auf Englisch?