How to render LISTS in React 📃
Summary
TLDRThis comprehensive tutorial delves into rendering lists in ReactJS, guiding viewers through the complexities of list rendering step by step. It begins by creating a functional component to manage a list, illustrating how to convert an array of strings into list items using JavaScript's map method. The video then explores sorting and filtering arrays, emphasizing the importance of unique keys for list items. It transitions to rendering arrays of objects, showcasing how to display additional properties like calories alongside fruit names. The tutorial also covers making the list component reusable by passing props, and concludes with practical tips on conditional rendering and setting default props and prop types for robust component design.
Takeaways
- 😀 The tutorial focuses on rendering lists in ReactJS, which can be complex but is broken down step by step.
- 📝 A new functional component named 'List' is created to manage the list, demonstrating basic component setup in React.
- 🍎 An array of fruits is used to illustrate rendering arrays, highlighting the conversion of array elements into list items.
- 🔄 The importance of using the 'map' method to transform arrays into list elements is emphasized for dynamic list rendering.
- 🔑 React's requirement for a unique 'key' prop for list items is discussed, ensuring React can efficiently update the DOM.
- 🔍 The tutorial covers sorting arrays with the 'sort' method, including custom sorting functions for alphanumeric order.
- 🏷️ The use of 'filter' method is explained to demonstrate how to display items based on certain criteria, like calorie count.
- 🔀 The process of making the 'List' component reusable by passing different lists as props is detailed, enhancing component flexibility.
- 🎨 Basic CSS styling is applied to the list components to improve the visual presentation of the rendered lists.
- ❗️ Conditional rendering is introduced to handle cases where lists might be empty, ensuring the UI adapts to data changes.
- 🛠️ The tutorial concludes with setting up default props and prop types for the 'List' component to ensure robustness and error checking.
Q & A
What is the main topic of the video?
-The main topic of the video is rendering lists in ReactJS, covering various methods and best practices for handling and displaying lists of data.
How does the tutorial start in terms of creating a list component?
-The tutorial starts by creating a new function-based component named 'list' in a JSX file within the source folder.
What is the initial data structure used in the tutorial for the list?
-Initially, an array of fruit names is used as the data structure for the list.
How is the array of fruits transformed into list items in the component?
-The array of fruits is transformed into list items using the built-in JavaScript 'map' method, which returns a new array of list item elements.
Why is it necessary to use a 'key' prop when rendering lists in React?
-It is necessary to use a 'key' prop to give each list item a unique identifier, which helps React efficiently update and re-render the list when items are added, removed, or reordered.
How can you sort the list of fruits in the tutorial?
-The list of fruits can be sorted using the 'sort' method, which can be applied directly to the array. The tutorial demonstrates sorting both lexicographically by name and numerically by calories.
What is the purpose of converting the array of strings into an array of objects?
-Converting the array of strings into an array of objects allows for more complex data structures, enabling the inclusion of additional properties such as 'calories' and makes it easier to manage and display the data in the list.
How does the tutorial handle empty lists or missing data?
-The tutorial uses conditional rendering to check if the list has elements before rendering it. If the list is empty or data is missing, it returns null or a default value to ensure the component doesn't try to render undefined data.
What is the benefit of making the list component reusable?
-Making the list component reusable allows it to accept different types of lists as props, increasing its flexibility and reducing code duplication across the application.
How does the tutorial enhance the list component with CSS styling?
-The tutorial enhances the list component with CSS styling by adding class names and defining styles for list categories and items, including hover effects, to improve the visual presentation of the list.
Why is it recommended to set up prop types in React components?
-Setting up prop types is recommended for validating the data types of props passed to a component. It helps catch errors and provides warnings during development, ensuring that components receive the expected data types and improving code reliability.
Outlines
📝 Introduction to Rendering Lists in React
This segment introduces the topic of rendering lists in ReactJS, emphasizing its complexity. The tutorial begins by creating a new functional component named 'List' within a JSX file. The component is initialized with an array of fruit names, and the video demonstrates what happens when this array is returned within the component. It then shows how to import and use this component in the main 'App' component. The focus is on converting the array of strings into an array of list item elements using the JavaScript 'map' method. The segment concludes with a discussion on rendering unordered lists and the importance of correctly enclosing elements within JSX.
🔑 Adding Unique Keys and Sorting Lists
The second paragraph delves into the importance of assigning unique keys to list items in React for better performance and state management. It demonstrates how to use the 'key' prop with the fruit names to avoid warnings. The tutorial then transitions into sorting the array of objects by different properties, such as name and calories, using the 'sort' method with custom comparison functions. The video also covers how to display additional information, like calories, alongside each fruit item and how to style the list items using bold tags. The segment ends with a discussion on sorting lists in both ascending and descending orders.
🍇 Filtering and Reusable List Components
This part of the tutorial focuses on filtering list items based on specific criteria, such as calorie count. It shows how to create arrays for low and high-calorie fruits using the 'filter' method and conditional rendering. The video then shifts to making the 'List' component reusable by passing different arrays as props, including a demonstration of passing an array of vegetables. The segment also covers how to handle empty arrays and the use of default props to ensure that components render even when data is missing. Lastly, it introduces the concept of PropTypes for type checking in React components.
🎨 Styling Lists with CSS
The fourth paragraph is dedicated to applying CSS styles to the list components. It describes how to add class names to the list items and category headings, and then details the CSS properties used to style these elements, including font size, color, text alignment, and hover effects. The video provides a step-by-step guide on styling the list category with a border, background color, and other visual enhancements. It also covers styling the list items to improve readability and visual appeal.
✅ Conditional Rendering and PropTypes
The final paragraph discusses conditional rendering to handle cases where lists might be empty. It explains how to use the logical AND operator for concise code when rendering components based on the presence of elements in an array. The tutorial also addresses the importance of setting default props and PropTypes to ensure that components behave correctly even when data is incomplete or incorrect. The segment concludes with a walkthrough of setting up PropTypes for the 'List' component, including defining the expected data types and shapes for the props.
Mindmap
Keywords
💡ReactJS
💡Component
💡Array
💡Map Method
💡List Item Elements
💡Props
💡Key Prop
💡Sort Method
💡Filter Method
💡CSS Styling
💡Prop Types
Highlights
Introduction to rendering lists in ReactJS with a step-by-step tutorial.
Creating a new functional component named 'List' in a JSX file.
Exporting the 'List' component for use in other parts of the application.
Using an array of fruits to demonstrate rendering lists in React.
Returning an array within a React component and the need for importing it.
Converting an array of strings into an array of list item elements using the map method.
Using arrow functions for cleaner and more concise code.
Creating an unordered list with JavaScript embedded within JSX.
Sorting an array of strings lexicographically using the sort method.
Transforming an array of strings into an array of objects with additional properties.
Adding a unique key prop to each list item as recommended by React.
Using a unique ID as a key for list items to avoid naming conflicts.
Displaying additional data, such as calories, alongside each list item.
Sorting the array of objects by properties like name or calories.
Filtering objects based on criteria, such as calories being greater than 100.
Making the 'List' component reusable by passing different lists as props.
Applying CSS styling to list components for better visual presentation.
Using conditional rendering to display lists only if they contain elements.
Setting up default props to handle missing or undefined properties.
Establishing prop types for better debugging and data type validation.
Conclusion and encouragement for further study and practice with rendering lists in React.
Transcripts
hey everybody I have a huge video for
you today today we're going to talk
about rendering lists in reactjs this
can be pretty complex we'll go through
it step by step what we'll do in this
tutorial is create a new component to
hold our list let's go to our source
folder create a new file I'll name this
component list this will be a jsx file
to finish creating this component this
will be a function based
component with the name of list then be
sure to export it export default
list we'll start with something very
simple we'll create an array of fruit
this will be const fruits equals think
of some fruit for me I'll pick an
apple
orange
banana coconut and a
pineapple let me show you what would
happen if we were to return our array
within our list component we will
return our array of fruits but we will
need to import it going back to the app
component we will import our list
component import list from a
location SL list.
jsx we need a return statement to be
sure you have one we will return a list
component and here is our list let me
zoom
in it's all one big string Apple orange
banana coconut pineapple heading back to
our list component we need to convert
our array of strings into an array of
list item elements we can use the
built-in map method to do that we'll
create a new array of list items the map
method is going to return a new array
after running it through a function
function const list items equals take
our original array of fruits use the
built-in map method then we'll either
pass in a callback a function expression
or an arrow function we'll use Arrow
functions because I like Arrow functions
for every fruit in fruits Arrow meaning
do this we'll create a new list item
element that has the text of our fruit
the array item we're not going to return
our fruits array we're going to return
an unordered
list we're going to insert some
JavaScript with curly braces we'll
include our list items it's an array of
list items and here's our array whoops
but I forgot to enclose fruit with curly
braces my mistake they are much better
better or if you prefer we can turn this
unordered list into an ordered list with
a pair of O
tags
o there they're all numbered that's how
to render a simple array if you're
working with an array of strings and
you'd like to sort this array beforehand
you can use the sort
method fruits. sort the sort method will
sort an array in place however this
doesn't work with numbers because we're
sorting
lexicographically we would treat numbers
and symbols as characters more on that
later let's go over example two we'll
convert our array of strings into an
array of objects each object will have a
name property and calories calories per
serving so let's enclose all of our
elements within a set of curly braces to
make them
objects I'm going to place each of these
objects on a new line just so that I can
read it more
easily each of these objects will have a
name property the name property will be
set to the original string for our array
the first object will have a name of
Apple let's add calories too calories
per
serving I did a quick Google search of
some of the calories per serving for
these fruits I don't know how accurate
these are but they seemed right our
first object has a name of Apple
calories is set to 95
name orange
calories
45 name
banana calories
105 name
coconut coconut
calories
159 name pineapp
example
calories
37 all right we now have an array of
objects there's a few changes we're
going to make if I run this again our
list is in rendering I need to display
the name property of each fruit fruit.
name
property we have one issue behind the
scenes I'm going to right click go to
inspect then go to
console
warning each child in a list should have
a unique key prop react wants us to
assign a key to each list item each key
should be unique in my array of objects
each fruit has a unique name I could use
that we will set the key attribute to
equal include some
JavaScript fruit. name that warning
should go
away
which it did if there's a possibility
that two objects can share the same name
you'll want to use some sort of unique
ID in a real world scenario if you're
pulling data from a database each row of
data is going to have some sort of
unique ID so we're going to mimic that
let's add a new property for an
ID ID will be one for Apple these will
be in ascending order orange will have
an ID of two banana is
three coconut is four pineapple is
five we'll set the key to be each
ID this would be much better than using
the name you can have a naming conflict
if two objects share the same name like
if these were people you could have two
people named Bob that warning should be
gone which it is react would like a
unique key for each item just so it can
more easily keep track of items being
inserted and removed along with each
element I'm going to display the
calories next to each
element so we'll make a few changes I'm
going to put these HTML elements on a
new line for
readability after the fruit's name I'm
going to add a
colon a non-breaking space character and
Pand nbsp for space oh then not a
semicolon forgot about
that then we'll ins some
JavaScript fruit. calories for the
calories of each
fruit I'll make it bold I'll enclose our
calories with a pair of bold tags which
is just
B now we're going to sort the items in
our list we'll do that before the map
method I'm going to sort our array of
objects by their name property we'll
take fruits
use the sort method the sort method will
sort an array in place we'll write a
custom sorting function we have two
parameters A and B A for the first item
B for the second then we iterate over
the entire
array we need an arrow meaning do
something to lexicographically sort
string properties within an array we can
use the following method we'll take the
name property of a use the built-in Loc
local or local some people say compare
method I misspelled
that yeah I can't spell
compare to b.n name that should sort our
array of objects by their name property
for reverse order let me turn this line
into a comment this is
alphabetical for reverse alphabetical
order we just have to replace a with B
and B with a there pineapple orange
coconut banana apple with apple being at
the
bottom let's sort by
calories fruits. sort this one's easier
again we have our parameters a comma
B Arrow the calories of a a.
calories minus b.
calories that one's easy we have
pineapple at the top followed by orange
apple banana
coconut this is in numeric
order for reverse numeric
order reverse
numeric or descending you could say the
calories of B minus the calories of a
now we have coconut at the top with
pineapple at the bottom with the least
amount of
calories in this next section I'm going
to demonstrate to you how we can filter
objects by a certain criteria we'll
filter anything that's greater than 100
calories we'll create a new array of
fruit that has low
calories we'll create a new array const
low cal
fruit equals take our original array of
fruits use the built-in filter
method we'll have one parameter of fruit
examine each fruit in our array of
fruits and Arrow then a condition here's
the
criteria check the calories property of
our
fruit if it's less than 100 filter it
and add it to a new array instead of
displaying our array of fruits let's
display our new array of low calorie
fruit oh that should be plural low cal
fruits when we create our array of list
items replace fruits with low cal fruits
and any instance of fruit with local
fruit
singular so we have three instances of
fruit let's replace
those let me clean this up a
little feel free to pause the video if
you need to write this
down we have three fruits that are low
calories the calories is less than 100
let's find any high calorie
fruits we can just copy this line of
code paste it but change the condition
examine the calories of each fruit
filter it out if the calories are
greater than or equal to
100 the name of this array will be high
Cal
fruits replace low calow fruits with
high Cal
fruits replace low cal fruit with high
Cal fruit
singular and do that for the other
instances as
well there we are we have two fruits
that are high in calories bananas and
coconuts that is US using the filter
method to filter out list items let's
replace High Cal fruits with fruits high
Cal fruit with fruit to display our
original
array for the next part of this lesson
we're going to transform this list
component so it's reusable with
different lists currently the way that
we set this up is that each list
component that we create has its own
list of fruit so we're going to make
some
changes let's cut our list of
fruits going to the parent component of
app we'll paste our list of fruits then
pass it as props to our list
component with our list component we
will have a key of items equals insert
some JavaScript our list of fruits let's
also add a category
key category equals for my category
let's say fruits eventually we'll add an
H3 heading we're now going to send all
of this data to the list component but
we have to set up props within the list
function we have a parameter of
props we'll access the items of props to
get our fruit
we'll create const item list equals not
to be confused with list items list
items is what we get after we map
it item list equals props do items and
remember that items is our fruits
array replace fruits with item
list replace fruit with
item do that here here and
here there's our list
again if you're going to sort or use the
filter method be sure it's item list not
fruits because now list is a reusable
component I'll add our category two
that's stored within props const
category equals props do
category currently we're returning a
single ordered list I'll also include an
H3 element
include some JavaScript we need curly
braces add our
category however with our return
statement we can only return a single
element or many elements that are
wrapped within a fragment let's create a
fragment that will enclose all of our
markup there we
are going back to our app component
let's create a new list just to make
sure that our list component is
reusable let's copy our array of
fruits paste
it we'll create an array of
vegetables the IDS will be 6 7 8 9
10 the name of my first item will be
potatoes calorie 110 per
serving
celery calories will be
15 carrots calories
25 corn calories
63
broccoli calories
50 now we should be able to create a new
list
component within our return turn
statement we're going to need a fragment
again we'll return a second list item
component the items will be vegetables
the category will be a string of
vegetables boom there we go here's our
second list
component so our list component is now
reusable we can pass in many different
types of lists to make this look better
let's apply some CSS styling we'll have
to set a class name
first our H3 element will have a class
name equal
to list-
category our ordered list will have a
class name of list
items all right going to our CSS
stylesheet index.css let's work on our
list category
first use dot to select a class list
category I'm just going to run through
these real quick I'm going to make sure
I'm zoomed in to 100 because I was
zoomed in
beforehand font size 2.5
em font weight will be
bold pick a
color I'm going to stick with hsl values
I'll set the lightness to be
20% I'll add a little bit of margin on
the
bottom 10
pixels text align
Center I'll add a
border three pixel
solid I'll add a border radius to round
the
corners
and a background
color pick a color again I'll use
hsl this one I pre-picked already
185
100%
50% that's not a bad looking color pick
whatever color you would like let's work
on our list item
elements we need to select the class of
list
items do list items select each list
item within this
class I'll increase the font size to be
2
em I'll remove the list style but you
don't have
to list style will be
none pick a color again I'm using hsl
values I'll set the lightness to be
25% text align
Center and margin will be
zero all right now when I hover over one
of these list items I'll apply a hover
effect take our class list items take
each list item access the hover sudo
class I'll change the brightness the
color will be something a little bit
brighter I'll set the lightness to be
45% and then the cursor will be a
pointer yeah not bad that's how we can
apply some CSS styling to list
components all right heading back to our
app component what if we have an empty
list for example with our fruits I'm
going to cut
it we can use conditional rendering to
render our list only if there's elements
let's put put those back we're going to
write some JavaScript we need some curly
braces let's take our array of fruits
access the length
property is it greater than
zero question mark if it is we'll return
our list
component colon if it's false we can
return null let's do that with our
vegetables
too take our array of vegetables
AIS the length property is a greater
than zero tary operator if it is return
our list
component if not we can return
null if one of these lists doesn't have
any elements we won't render that
component there is a short hand to the
tary operator we don't need to write or
else return null what we'll use instead
of the trary operator is the and logical
operator we can effectively Short
Circuit the first
expression then we don't need colon null
it's a little less
code our list component will always be
true because it
exists however the first expression
might not be so if this condition is
false we don't render this if it is true
we will render this let's try that again
let's remove these
elements we don't display the fruits
list
component and we will not display the
vegetable list
component this is known as short
circuiting one thing to consider what if
our category is missing let's remove our
category from
fruits well I would like to add some
sort of placeholder here or what if one
of these arrays was
missing well nothing displays not even
vegetables we should add some default
props in case one of these properties is
missing so going back to our list
component before we export it let's set
up some default props take our component
name list. default props equals within a
set of curly braces let's set our
category category
property to be category as a placeholder
if for some reason these components
don't have a
category we'll add a placeholder of
category which at least looks better if
we're missing an array that's a bigger
problem let me go to inspect then
console we're trying to map something
that's undefined we have no array to
work with so nothing is rendering so as
a backup Within default props let's set
our items to be an empty
array items will be an empty
array if one of these arrays was missing
for some
reason at least the category is
displayed as well as the subsequent
components at least something will
display okay then lastly as good
practice if we're accepting props we
should set up prop types I'll walk you
through it if you're just joining us
with prop types if the incorrect data
type is passed into props when we debug
it'll give us a
warning to use prop types we have to
import it at the top of our list
component we will
import prop
types
from prop
types take our component of
list
list. prop
types
equals set of curly braces for our
category this will be a
string category colon
space prop types do
string add a comma for another line okay
this is where it's going to get tricky
we have an array of
objects we'll access the items
property items colon
space to types I'm going to move down a
little
bit dot we have an
array
array of we have an array of
objects prop
types do shape method we have to define
the shape of each object each object is
going to have its own data types we have
a number string then
number we're defining an object we need
a set of curly
braces ID
colon prop types.
number comma for another
property I'll put the next one on a new
line for
readability we have a name property
which will be a string prop types.
string then
calories
prop types.
number and that's
it let's head back to our app
component our prop types should raise a
warning if some of our data is of the
wrong data type for example let's say
that calories is now the string Apple
maybe somebody mistyped it
twice you can see that right here it
changed let's go to
inspect
console
and here's our warning because we have
prop type set up invalid prop items
index zero calories of type
string if we didn't have prop type setup
we wouldn't receive that warning this
may go unnoticed it is good practice if
you're accepting props to also set up
prop types it's a little more
complicated if you have an array of
objects but here are the steps all right
everybody I know this was a massive
topic thank you all for watching feel
free to take some time to study and work
with this before moving on to the next
topic if you would like we did Cover a
lot of material and well those are
various ways in which we can render
lists and
react
関連動画をさらに表示
How to render lists | Mastering React: An In-Depth Zero to Hero Video Series
#15 String Interpolation | Angular Components & Directives | A Complete Angular Course
Introducing Blazor Components [Pt 3] | Front-end Web Development with .NET for Beginners
What is indexing of list? | Avoid using index as keys
Explaining Figma Components Like You’re Five (Simplest Way Possible)
Understanding Props and PropTypes in React | Complete React Course in Hindi #6
5.0 / 5 (0 votes)