02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Using the JSX and ES6 Spread Features

Tutorial: Using JSX and ES6 Spread Features

In this tutorial, we explore the powerful spread operator and its applications in ES6 and JSX. By using the spread syntax, we simplify code, enhance reusability, and create more dynamic React components. Let's dive in!


What is the Spread Operator?

The spread operator (...) is a syntax introduced in ES6 that allows iterable elements (like arrays or objects) to be expanded into individual elements. It’s particularly useful in React for:

  1. Passing Props Dynamically
    • Simplifies the process of distributing properties to components.
  2. Handling Variable-Length Arguments
    • Aggregates arguments into arrays or separates them into individual items.

Using Spread in Functions

Consider a function where you want to sum a variable number of arguments:

function addNumbers(...args) {
    return args.reduce((total, num) => total + num, 0);
}

// Usage
console.log(addNumbers(10, 20, 30)); // Output: 60

Here, ...args aggregates all arguments into an array, which we process using reduce.


Using Spread in JSX

The spread operator shines in JSX for prop distribution. Instead of manually assigning props:

<FooterItem title="Contact Us" content="info@example.com" />

You can simplify by spreading a data object:

const footerData = { title: "Contact Us", content: "info@example.com" };
<FooterItem {...footerData} />

This approach:

  • Reduces redundancy.
  • Makes components dynamic and adaptable to data changes.

Combining Spread with Rest

Rest parameters (...args) collect items into arrays, while the spread operator expands items. They work seamlessly together:

function duplicateAndSum(first, ...rest) {
    const sum = rest.reduce((total, num) => total + num, 0);
    return first * sum;
}

console.log(duplicateAndSum(2, 10, 20, 30)); // Output: 120

Here, first gets the first argument, and ...rest aggregates the remaining arguments into an array.


Applying Spread in React

In a React application, the spread operator improves component reusability. For example:

  1. Define Model Data

    const footerModel = [
        { title: "Location", content: "123 Main St" },
        { title: "About Us", content: "Committed to excellence." },
    ];
    
  2. Render Components Dynamically

    footerModel.map((item, index) => <FooterItem key={index} {...item} />);
    
  3. Inside FooterItem

    function FooterItem({ title, content }) {
        return (
            <div>
                <h3>{title}</h3>
                <p>{content}</p>
            </div>
        );
    }
    

Debugging and Validating Props

While the spread operator simplifies code, it's critical to validate props for errors. In the next tutorial, we’ll explore how to use React's built-in prop validation tools to ensure data integrity.

This lecture introduced the spread operator in ES6 and JSX, showing how it streamlines prop management and enhances component flexibility. Stay tuned for the next topic on validating React props for robust application development!

Video Transcript

00:00As we're creating incredibly reusable components in this
00:04lecture we're gonna go through to understand
00:07how do the spread features work in React and in ES six
00:11and in JSX in general.
00:13Let's jump right into it where we'll learn what spread is
00:16how to use it in JSX and how to use it in E ES six.
00:22Alrighty. We're definitely getting close.
00:23So let's go ahead and before we make things dynamic,
00:26let's go right back into our code editor
00:28and I'm just gonna find an empty space here
00:30to talk about some more fun things that are new in E ES six.
00:35Beautiful. So we add our hey function.
00:37Let's just go ahead here and just add more.
00:41Alright, so let's say we have a function
00:44and in our function,
00:45or even more than that, let's say that we,
00:47we basically wanna add a lot of digits together
00:50and we have here this add function.
00:52Now, historically add stuff, add numbers, how about that?
00:57Add numbers. Now the problem is
00:59with our add numbers function is we don't wanna have a set
01:02amount of elements that come in.
01:04We could send it as an array,
01:05but if we send it in as an array,
01:07and then let's say we do a console log
01:10and we call add numbers,
01:13and we send in, let's say 10 and 10.
01:15Okay, so we send two. That's easy.
01:17If I send in an array, not that hard,
01:19but then I have to use an array, which kind
01:21of less is less fun.
01:23Now, in ES five there was a property that is called
01:26arguments, which was very nice.
01:28And with this arguments, if I go ahead here
01:30and I return our arguments and I just go ahead
01:34and run this.
01:35And by the way, let me just go ahead here for a second.
01:38Not in our footer,
01:39and nevermind, I wanted to delete some of those traces
01:41that we have so we could take a better look at it.
01:43But let me just add here some extra noise so we could, uh,
01:47spot it more easily so we could see
01:49that our arguments is return back
01:51and we could see that we have a lot
01:52of stuff in this arguments method.
01:55And if I, uh, look into that, first of all, it's, it's,
01:58you know, I can't, I, I can't, uh,
02:00let me just do a two string if I could.
02:03I don't think it does two strings.
02:06Yes, no, no, it's an ar you can't,
02:08you can't see it unfortunately.
02:10So basically I would have to go like one by one
02:12and send it in, but we're not gonna do that.
02:14Let's look at how we do it in ees six.
02:15Now in e ES six, a really cool way is you just type three
02:18dots and then ARGs or props or whatever you wanna call it.
02:22Really this is just any variable name.
02:24And by typing your three dots
02:26and then that what is actually is gonna happen is it's gonna
02:28return back as a type of array you could say,
02:32or a built in type of array,
02:34which will give you direct access to
02:36that array information if you wanted to,
02:38or in our case, I could go ahead
02:40and do a four, let ARG
02:45in ARGs console log
02:50ARG and return.
02:54Let's just return zero for a second.
02:56And if we take a peek at here, we'll see that. Now we could
02:58Go through argument by argument or I could go for of,
03:06and then I would get the actual numbers.
03:09So by getting the actual numbers inside of that loop,
03:12I could go ahead and now say, okay,
03:13so let me just create your uh, um, a let, right,
03:17and I'm gonna call it total.
03:19And initially its total is equal zero.
03:21And then I'm gonna go into my total
03:23and add into that total the arg.
03:27And then I'll just go ahead
03:28and send our arguments total back and we should get our 20.
03:33Beautiful. That's exactly the value.
03:35And if I go ahead here
03:36and just send your 3, 2, 30, 10, 5,
03:39it doesn't really matter, it will add up the numbers
03:41and give me that perfect number.
03:43So arguments is an incredibly useful, um, logic set.
03:48And I wanna show you just one more thing
03:49that you could do with this logic.
03:50So, so how about in a situation that we want
03:53to add numbers and duplicate.
03:55So let's say I'm gonna create a function
03:57and I'm gonna call it dupe first by
04:02total of rest.
04:04Now obviously this is a silly function name
04:07and obviously this is not that logical,
04:09but really in this situation, what do I want?
04:10I wanna separate the first argument
04:12and turn that into the b the duplicator
04:15of all the connection of all the rest of the values.
04:18In this situation, what I would wanna do is I could go ahead
04:21and, and and, and go through the process of these arguments,
04:25but instead of that, well, on top of
04:27that I could say, okay, the first one.
04:28So it's gonna be like, let's say this is uh, um, a,
04:31I'm gonna call it and then I'm gonna type here
04:351, 2, 3, ARGs.
04:37Now I could have put a few of these properties.
04:39So now if I go ahead here in my console, log A,
04:43if I don't have an error here and I have a small error
04:46and that's because I didn't put here a comma,
04:48I thought I need to comm, I wasn't a hundred percent sure
04:51and if it refreshes now we'll see that.
04:53Now we're getting, oh, we're never calling it right?
04:56So let's go ahead and call that method
04:58and instead dupe first by total of rest.
05:01And if we do that, we'll see.
05:02Okay, so we're getting that first value. Beautiful.
05:05The next thing I want to do is I want
05:06to send these arguments to this ad number.
05:08So I could do something that already we could have done in
05:10ES five previously.
05:12So I'm gonna call add numbers,
05:14but instead of calling it directly, I'm gonna call the apply
05:18and I'm gonna send it the actual ARGs that are left.
05:21So I'm gonna send it the stuff that we actually wanna send
05:23for our add numbers, passing it over like a hot potato.
05:26Now by doing that,
05:27what I've done is I've actually got the value back
05:30and if it recompile, oh here we go, 57.
05:34Last but not least, all that's left for me
05:36to do is I'm just gonna return here.
05:38The value of a times the value
05:40that comes back from applying the value of ad numbers.
05:43And I've got myself the value of the duplicate
05:46of the first total of the rest.
05:49And through that we've learned how to work
05:51with the spread properties.
05:54Really, really cool stuff.
05:55Now before we wrap things up, let's
05:56Just see, see that it works. And we see
05:57here that 570, wonderful,
06:00let's go back into our footer and use this logic
06:02and I'll show you how do you use spread inside of JSX.
06:07Now in JSX, if you just find our footer elements somewhere
06:10down below here, here we go.
06:12I'm gonna go ahead and just delete this
06:14value of this title Ben.
06:15And I'm gonna open and close a round bracket just
06:17like all the times before.
06:18Only this time I'm gonna type 1, 2, 3 dots just like
06:22with our regular function spread.
06:25And then I'm gonna type the variable name
06:27or object that I want to send as the properties.
06:29So in this case, I'm gonna go ahead
06:30and I'm gonna say, okay, so our model,
06:32if we take a look at our client that we're sending in
06:35for the footer, this is the structure.
06:37So I want to go to the array's first position
06:39of our footer model, which is called, which is called,
06:42which is called data.
06:44So let's go ahead. So I'm gonna go to props this stop props,
06:49do data, and I wanna go to the first item.
06:53So I'm basically sending the first item in our props.
06:55Now technically everything here should continue working.
06:59So if I go ahead here, because in my text footer it's
07:01expecting title and content.
07:03So it's really breaking it out
07:04and sending it as individual items.
07:07And if I check it out, we'll see that.
07:08Now we have our location. Notice how we have your br.
07:11So we're gonna have to figure out a solution for it
07:13'cause it's rendering it as basic text
07:15and not as an actual br.
07:18Next oto, we're gonna wanna send it for the item
07:21that is another text one, which we know.
07:23The third one is the text one as well. So here we go.
07:26Let's send it Oto for our third item,
07:27our second item in the thera, uh, second position 0 1, 2.
07:32Um, and if we go ahead and check that, we'll see
07:34that now we're sending in that value as well.
07:36But do we have here in error, no, no error,
07:39but our data interesting
07:40that we're not getting our body here, is it
07:43'cause it's not sending in or it's
07:44because let's check in our inspector to see if
07:46that actual data is being sent in.
07:48So, uh, container row,
07:53we want our third item.
07:55And in our third item we can see
07:56that we have an empty paragraph on contrary
07:59to the first item that our content is going through.
08:01If we take a peek, let's take a peek at our client data
08:04to see why is that, um, I
08:09con connect that would do it.
08:12Content save.
08:13And if we go back in there
08:15and refresh, we'll see that Now our content comes in.
08:17And that really leads us to our next topic
08:19that we're gonna talk in the next lecture.
08:20We got here a bug, but it was really, really hard for us
08:23to discover that bug, although it wasn't hard for us.
08:26'cause our application is small,
08:27but as our goal is to create reusable components,
08:30they're not incredibly reusable.
08:33If we don't have a way to tell developers, Hey,
08:35there's a problem with the data that you're sending in.
08:38And that's exactly the topic
08:39that we're gonna be covering in the next lecture.
08:43In this lecture we learned how
08:44to use spread in ES six and JSX.
08:48In the last next lecture, we're gonna talk about how do you
08:51validate your properties
08:52and how do you do it in the development environment using
08:55built-in validations that exist inside
08:57of every single React component.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!