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

Building a Reusable Bootstrap React Button

In this tutorial, we will create a reusable React component for a Bootstrap button. You'll learn how to design components with flexibility, use JSX to manage props dynamically, and implement best practices for modular React development.


1. Introduction to Reusability in React

Reusability is at the core of React development. By creating components that are modular and dynamic, we minimize redundancy and ensure scalability in our applications. In this tutorial, we build a reusable Bootstrap button component, illustrating how React and Bootstrap together can simplify and enhance your development process.


2. Setting Up the Button Component

Step 1: Create a New Button Component

  1. Inside your project’s src directory, create a Bootstrap folder.
  2. Add a new file named Button.js.

Step 2: Define the Component Structure

In Button.js, start by importing React and creating a basic class component:

import React from 'react';

export default class Button extends React.Component {
  render() {
    return (
      <a href="#" className="btn btn-primary">
        Click Me
      </a>
    );
  }
}
  • React Component Basics:
    • The class Button extends React.Component, making it a React class component.
    • The render method defines what the component will output to the DOM.

Step 3: Use the Button Component

To use the new Button component, update the App.js file:

import React from 'react';
import Button from './Bootstrap/Button';

export default class App extends React.Component {
  render() {
    return (
      <div>
        <Button />
      </div>
    );
  }
}

With this setup, the app renders a simple Bootstrap-styled button.


3. Enhancing Component Flexibility with Props

To make the Button component reusable, we replace hardcoded values with dynamic properties using props.

Step 1: Modify the Button Component

Update the Button.js file to accept props dynamically:

import React from 'react';

export default class Button extends React.Component {
  render() {
    const { href, className, children } = this.props;

    return (
      <a href={href} className={`btn ${className}`}>
        {children}
      </a>
    );
  }
}
  • Props Destructuring:
    • href, className, and children are extracted from this.props.
    • children allows you to pass content inside the button tags dynamically.

Step 2: Pass Props from App.js

Customize the button from App.js:

import React from 'react';
import Button from './Bootstrap/Button';

export default class App extends React.Component {
  render() {
    return (
      <div>
        <Button href="https://example.com" className="btn-primary">
          Go to Example
        </Button>
        <Button href="https://another-link.com" className="btn-secondary">
          Another Link
        </Button>
      </div>
    );
  }
}

4. Using Spread Syntax for Cleaner Prop Handling

React allows the use of the spread syntax (...props) to pass all props at once, reducing redundancy:

Step 1: Update the Button Component

Replace the destructuring in Button.js with the spread operator:

export default class Button extends React.Component {
  render() {
    return <a {...this.props} />;
  }
}

Step 2: Simplify Button Usage

In App.js, pass all attributes directly:

<Button href="https://example.com" className="btn-primary">
  Go to Example
</Button>
<Button href="https://another-link.com" className="btn-secondary">
  Another Link
</Button>

This approach ensures that all valid attributes, such as target="_blank", are automatically supported.


5. Error Handling and Validation

To avoid potential issues with unsupported props (e.g., disabled on <a> tags), we will add validation in future enhancements. React's prop types or a filtering mechanism can ensure only valid attributes are passed to the DOM.


6. Conclusion and Next Steps

In this tutorial, we built a reusable Bootstrap button component and enhanced it with dynamic props and the spread syntax for flexibility. These principles lay the foundation for creating sophisticated, reusable components in React.

In the next tutorial, we will explore creating dynamic JSX tags to further enhance component reusability and ensure compatibility with Bootstrap's extensive documentation.

Video Transcript

00:00In the last lecture, we created our first E es six class
00:04and for that matter, our first ES six component of React.
00:08In this lecture we're gonna take a step deeper
00:10by talking about how to create reusable bootstrap elements,
00:14in this case a button.
00:16So in the process we're gonna understand better how
00:18to create a good strategy to create components and react,
00:22and we'll build out a bootstrap button into
00:26that react component.
00:27So we're just gonna mix this, the two topics together.
00:30Let's go ahead and do that. In many ways, bootstrap
00:34and react aim to simplify web development.
00:38Now one of the steps really in React that simplify things,
00:43although this didn't really simplify much yet, is the idea
00:46of reusability and componentizing or modulary.
00:51In the, in the no terms would be modules.
00:53But in the terms of react, it would be components
00:56where you would try to capture reusable elements
01:00and make them the best at the smallest thing that they do.
01:04For example, in the case here of a button
01:06that we're creating, using the AAG
01:08and the class names button
01:10and button primary, really we would love to be able
01:13to create a component here then
01:15that then we could leverage and reuse.
01:18So let's go ahead and do that.
01:19And in my source folder, I'm gonna go ahead
01:22and create a new folder called Bootstrap.
01:25And in the bootstrap folder, I'm gonna go ahead
01:27and create a new button file.
01:33Let me go ahead and save it.
01:35And we created our new button file.
01:37Now same applies, we're always using React here,
01:40so I'm always gonna start with import, react from React
01:45the next step, I'm also always gonna create a class
01:48and I'm gonna also export it.
01:49So let's go ahead and just do that right away.
01:51Export default class button
01:57extends react component.
02:02Okay, so that's our class.
02:04The next step is we wanna also create a render method.
02:07And this is true to every single React component
02:11and return of value.
02:12Now in this case, the most basic value
02:14that we would wanna return is, let me just grab this whole
02:17construct and I'm just gonna cut it out out of our sample
02:21and literally just oopsie, I just undo that.
02:25Cut that. Come right in here, semicolon.
02:30Let's word wrap this baby.
02:32And why is word wrap not a default in this application?
02:36Oh, come on. Alright, so we're saving it.
02:38So we've just created the button.
02:40Now we wanna share this button with our app.
02:43And again, to do that I'm gonna import it.
02:45So I'm gonna go to my import
02:47and relative to where I am right now,
02:49which is the app folder, I'm gonna ask for the button from
02:53the current folder I'm in bootstrap
02:57slash button.
02:59And there we go. We just imported the button.
03:02Now that we have a button. And don't forget,
03:04we have your uppercase.
03:05So it's not HTML anymore.
03:07Now it's actually fetching the class
03:09name whenever we will use it.
03:11So because I have there an uppercase name,
03:13if I just go ahead and save this
03:14and go back into my application,
03:16I should still see everything.
03:17If I don't have an error, let's see what my error is.
03:20Module not found error, cannot find file or directory.
03:24It cannot find the button.
03:25So let's see if we have your spelling error.
03:28And if we take a look at it, it's bootstrap, bootstrap,
03:33but ton but ton.
03:34So all here looks good to me,
03:36but let's see if in our structure here, if there is anything
03:40that stands out as problematic, which there isn't.
03:43So let me just go ahead and save this one more
03:44time to double confirm.
03:46Save this one more time to double confirm
03:49and it still cannot find our button file,
03:53but let me just take a look here.
03:55Source bootstrap slash button.
03:59And it's saying that even button js doesn't, doesn't exist,
04:02although source bootstraps,
04:05I must have your file name issue.
04:07So it's boot sap, nah, bootstrap
04:11and it's definitely not bootstrap.
04:12So lemme go into that folder.
04:14Let's find our folder
04:17and let's change that from boots to bootstrap.
04:21And sometimes debugging is part of that process.
04:24And let me just also make sure that I close my bootstrap
04:27so I don't uh, do it, uh,
04:30rewrite it again in the wrong file structure.
04:32And if we go ahead here and take another peek,
04:34I'm gonna have to refresh 'cause I changed the folder
04:36outside of our environment.
04:38But let's see. First of all,
04:41bootstrap does not exist still, so I'm still having an issue
04:45with my definition of my structure here.
04:49So let me just double, triple, quadruple check.
04:53So boot strap, boot strap.
04:57Yeah, it looks brilliant to me.
04:59So lemme just change something really quickly just
05:01to make an error again.
05:02So to force it to refresh to recomp,
05:05compile more accurately.
05:07And I'm gonna go ahead here and save this again
05:09and go back in there and see if that would sort it out.
05:12Absolutely. So what the problem was is even though I clicked
05:14on refresh, it didn't recompile my code
05:16because it's supposed to actually run internally.
05:18So it had a cached version.
05:20So by clicking on refresh there, uh, by typing something,
05:23saving it, forcing it to refresh
05:26and then undo it, I made sure that it came in.
05:28So again, so, so what I've just created is a button
05:31that I could now reuse
05:33and I could reuse it for example, three times.
05:36And if I go back into my application,
05:38I just have three buttons, although not incredibly useful.
05:41But let's go into our button here
05:42and make it a little bit more smart
05:45because one of our problems with our budget currently is
05:48that we have everything baked in in our content.
05:52In reality, what we would love to do is take all
05:55of this content, cut it outside of our component,
05:59go into our button structure here
06:02and lemme just delete all this stuff here
06:04and literally just send it in as parameters inside
06:08of our button element.
06:10Now to be able to do that, it's quite simple
06:12and the easiest, well one way
06:14to do it, let me show you this.
06:15The first way to do it for one is literally just going one
06:20by one and defining all of our elements.
06:23So if I go ahead here
06:24and I just paste the same values in here again this time
06:28around after I've pasted it in, instead
06:30of actually I addressing
06:32and typing in that content directly, I'm gonna go ahead
06:35and use a JSX controller that enables me
06:40to input content inside of our XML structure
06:44or HTML structure or JSX structure more accurately.
06:47And I'm gonna go ahead and ask for this step props,
06:50which will connect to the properties of this specific class.
06:54And then I'm gonna go ahead and take that class name
06:56and lemme just go ahead and replicate this over in the,
07:00our three elements here.
07:02So our first item is our HR.
07:05So let's go ahead here and HRF and then we have our target
07:10and let's put here our target
07:14and that will do the trick.
07:15So once I've done and configured all of these items,
07:18if I go back into my application, I'll still have a button
07:21and once the refresh has been done, if I click on it,
07:24it will open up zero to geek as it's done, as
07:26as it has done previously.
07:29Now, but the problem with this is that I have
07:31to actually physically write down every single item,
07:34which is probably cumbersome,
07:36especially in this type of situation.
07:38A much better solution is actually a really cool one
07:42and I'm gonna delete all of this.
07:43And what I'm gonna do is open a curly bracket,
07:46close a curly bracket with nothing there
07:49and then I'm gonna type three dots, 1, 2, 3,
07:52and I'm gonna type this dot props
07:53and I could have put here any variable
07:55but what we'll do, it's basically gonna
07:57extract out all the properties here
07:59and append them into this A item.
08:01And now if I go ahead and save this,
08:03everything should still continue working without needing
08:05to retype everything.
08:07Again. Beyond that, if I go ahead
08:09and I create another version in our app, I just go ahead
08:13and create another button
08:15and for our next button I'm just gonna go ahead
08:19and change the values.
08:20So I'm gonna still go to zero to geek,
08:22but this time around I'm not gonna use blank.
08:25And instead of using a primary button, I'm going
08:28to use a secondary item.
08:31And by the way, there's primary button, secondary
08:35danger link.
08:36So for example, if I put here danger,
08:39then I'm gonna have the danger default color coming through
08:42and if I go ahead and test this out, we'll see
08:44that we'll have your discover things which if I click on it
08:47will override without that target
08:49'cause it doesn't exist inside.
08:50While if I go for discover things it will open up
08:53in a new panel.
08:55So that's really the basic basic of creating,
08:58of really reusable component.
09:01Although we're almost there, we're not completely there,
09:04we we're, we're definitely gonna extract out a lot of the
09:07built in features of re uh, of Bootstrap.
09:10We don't wanna lock them in a hard code them inside
09:13of our component, but we definitely wanna improve our
09:16component so it doesn't throw errors.
09:18So in the case for example, if I put inside your property
09:21that is not supported by the Atag for example, I go ahead
09:25and I add your disabled,
09:27which is technically not supported in the atag
09:30and if I go ahead and look in my browser
09:33it will should give me some sort of a warning.
09:36Although let me go ahead and put yours something
09:38that is completely not not supported.
09:40Let's go ahead and I'll just call this fun equals yes
09:44and I'm gonna go ahead and save this.
09:45And if I go back into my application when it re renders,
09:48it's gonna throw an error
09:49and is gonna tell me, whoa, fun is not something
09:51that belongs into the A tag.
09:54Although I might wanna let users
09:56add things that don't exist.
09:58Theoretically speaking in that situation, we're gonna want
10:01to figure out a way how to extract out only the things
10:04that are supported and also send
10:06inside a better button component.
10:08So lemme just go ahead and delete this
10:10and that's something that we're gonna start working on in
10:12the next lecture.
10:15In this lecture we really mixed in our bootstrapping
10:18and our react and kinda showed the process
10:20of creating reusable components in React.
10:23In the next lecture we'll continue down that path
10:25as we'll create dynamic J js six tags to help us comply
10:30with the documentation of Bootstrap.

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!