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

Understanding JSX Spread in Depth

In this tutorial, we’ll dive into the JSX spread operator and explore how it simplifies component development in React. By the end, you’ll know how to use the spread operator to manage properties dynamically and optimize your components for reusability.


Why Use JSX Spread?

The JSX spread operator (...) is a powerful tool that allows you to pass all properties of an object as attributes to a component. This eliminates redundancy and streamlines your code by avoiding the need to manually specify each property.


Step 1: The Problem with Hardcoding Attributes

In a basic React component, attributes like className or type are often hardcoded. This makes components rigid and harder to reuse. For example:

<button className="btn btn-primary">Click Me</button>

If every button in your project needs these classes, hardcoding them is inefficient and repetitive.


Step 2: Using the Spread Operator

  1. Basic Syntax
    Use the spread operator to dynamically apply properties.

    const props = { className: "btn btn-primary", type: "button" };
    return <button {...props}>Click Me</button>;
    
  2. Combining Default and Custom Properties
    To add default properties while allowing overrides, combine the spread operator with custom logic:

    const defaultProps = { className: "btn btn-primary", type: "button" };
    const combinedProps = { ...defaultProps, ...this.props };
    return <button {...combinedProps}>{this.props.children}</button>;
    
  3. Dynamic Class Names
    Add default classes like btn dynamically:

    const className = `btn ${this.props.className || "btn-primary"}`;
    return <button className={className} {...this.props}>{this.props.children}</button>;
    

Step 3: Enhancing Button Flexibility

Here’s how to take it further:

  1. Support Multiple Button Types
    Define default and optional classes for different styles:

    const buttonClass = `btn btn-${this.props.variant || "primary"}`;
    const combinedProps = { ...this.props, className: buttonClass };
    return <button {...combinedProps}>{this.props.children}</button>;
    
  2. Adding Features
    Add features like size (btn-sm, btn-lg) or full-width (btn-block):

    const sizeClass = this.props.size ? `btn-${this.props.size}` : "";
    const blockClass = this.props.block ? "btn-block" : "";
    const className = `btn ${sizeClass} ${blockClass}`;
    return <button className={className} {...this.props}>{this.props.children}</button>;
    

Step 4: Testing the Component

Test the component with various properties:

<Button variant="secondary" size="sm">Small Button</Button>
<Button variant="danger" block>Full-width Button</Button>
<Button>Default Button</Button>

Expected Output:

  • A small secondary button.
  • A full-width danger button.
  • A default primary button.

Best Practices

  1. Override Safely
    Apply defaults first, then override with user-provided props using the spread operator.
  2. Avoid Repetition
    Use helper functions or variables to generate dynamic class names.
  3. Validate Props
    Use PropTypes or TypeScript to ensure correct usage.

Conclusion

By using JSX spread effectively, you can simplify your React components, reduce redundancy, and make them more reusable. This is particularly useful in UI libraries where multiple variations of a component (like buttons) are common.

In the next tutorial, we’ll continue enhancing the button component to support even more features and align with Bootstrap’s documentation.

Video Transcript

00:01A good react component is one that is reusable,
00:03and we're gonna be using JSX spread to be able
00:06to make our things just so much better.
00:09And in the process we're gonna learn what that spread is,
00:12how to use it in JSX,
00:13and also use React Properties to make our component just
00:18so much more dynamic.
00:21Our goal when we create components is to try to make them
00:24as reusable and as easy for us to create.
00:28Now if you take a look at our button, you'll notice
00:30that there's a lot of repetition for one, that usage
00:33of button, well that's a small repetition,
00:35but every single button will have that class.
00:38And as such, it really doesn't make sense
00:40to need to type it each time.
00:41We would love to actually put it into our button construct.
00:45So to do that, it's actually very simple.
00:47I'm just gonna go ahead and create another cons.
00:50And this time around I'm gonna fetch out
00:52or extract out the value
00:55and append into the value that we have,
00:58the actual button value.
01:00So again, I'm gonna go ahead here
01:02and I'm gonna set my button
01:03and I'm gonna say, call this class name
01:07and I'm gonna go ahead and fetch the this props dot
01:10class name.
01:13But beyond that, I don't, I don't wanna only grab it.
01:15What I wanna do is I'm gonna go ahead here
01:17and just add that button plus it
01:21with a space just as it needs to be.
01:24Now, right now we created a class name
01:26and we could very easily just go into our tag,
01:29add a new property,
01:30and assign it a value of that class name.
01:33But if we go ahead here,
01:34and let me just go ahead also in our app
01:36and delete out that button
01:38because we want that to come in dynamically.
01:40If I save things and check it in my browser, you'll see
01:43that it actually doesn't come in.
01:45Now the reason is very simple is
01:47because the this dot props is overriding it.
01:50The spread parameter, which is called,
01:53is overriding our class name.
01:55Now, we could also extract out all these items,
01:58create an object, send that object,
02:00that would is without it,
02:01but probably the easiest solution is to let it put in
02:05and once it's done, just put it in again
02:07after it's been set.
02:08So after it's been said, it will then go through
02:11and override that overriding
02:13or that was created, making sure
02:16that our button will be entered in as well.
02:19Now I wanna add a little bit more stuff.
02:21So even before we go ahead
02:22and add another feature, I wanna introduce you
02:25with more different things that you could do
02:27with your buttons.
02:29So our button is the primary button,
02:31but I could also set our button to be a button pri.
02:35Well, let's do this button.
02:37Um, uh, well, let's do it secondary
02:43dash outline.
02:45And for our button danger, I'm just gonna go ahead
02:48and set it to be danger outline only.
02:52And I could go ahead
02:53and say, by the way, this is gonna be a button that is small
02:56and that will
02:58Do for this button.
02:59And let's go ahead and create another button
03:01that will live out of the paragraph area.
03:04And I'm gonna create this as a button that is going to be,
03:08for example, a button that acts as a link.
03:13So look visually, more like a link,
03:15but we also want it to have a button, primary outline or,
03:20or a little, let's just have it a button, primary outline.
03:23And I'm gonna go ahead and I'm gonna make that button large.
03:26And I'm also gonna make that button take the full block.
03:30Okay, so I've just added most of the features
03:32that are available for a button beyond one,
03:34which is disabling, which we'll talk about
03:37that one separately in a minute.
03:38But if I go ahead and save this
03:40and I go back into my application, we'll see that.
03:42Now we should have a massive button.
03:44We'll have your one button that's, uh, larger,
03:47one button that is smaller.
03:49And really what's, what's going on here is the
03:52secondary outline is overtaking the primary.
03:55So in this case, let's leave that as the primary
03:58and leave this item as the outline item.
04:02So w with that said, we're still, we have here a lot
04:05of repetition and the big repetition here is the usage
04:07of button, because it's a given.
04:08This is a button. So ideally it would be really cool if we
04:12could just not even type that, that anytime we have a dash,
04:15then it would know to put inside a button.
04:17You know, it's very minor,
04:18but it doesn't have to be mandatory.
04:20So if someone uses the regular way to do it in,
04:23in Bootstrap, then it will work.
04:25But we wanna just create a facilitator
04:27to make typing a little bit faster for lazy developers such
04:31as myself.
04:33So the idea itself is what I'm gonna do
04:35or what we're gonna do in the next lecture is basically make
04:37that button part a little bit more dynamic.
04:40So our button will be able to extract that
04:42or add that data dynamically in
04:45whenever an item is being created in this lecture,
04:48we took our component even a step further in the level
04:51of dynamics that it has by leveraging properties
04:55and leveraging that spread feature in the next lecture.
05:00We'll continue down this path
05:01as we add more features into our button component
05:04to match up to the official documentation.

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!