DEV Community

Cover image for Step by Step Guide to using Reactstrap for building Web Apps With Sample Projects
Sixtus Anyanwu
Sixtus Anyanwu

Posted on

Step by Step Guide to using Reactstrap for building Web Apps With Sample Projects

Introduction

There are lots of UI component library out there for developing react powered web applications. Reactstrap is one of such sleek UI libraries but sometimes gets confused with React Bootstrap which is also a UI component library that uses BootstrapCSS behind the scenes for its component styles.

In this article, we will learn how to use Reactstrap, the differences between reactstrap and react bootstrap, using reactstrap to build two simple yet cool projects. You will get exposed to the several components that is available on reactstrap how to best use them.

Table of Contents

Pre requisites

  • Nodejs 16+
  • Text Editor preferably VS Code.

What is Reactstrap?

Reactstrap is a component library for building web apps with Reactjs. It includes a collection of reusable components that may be used in apps written in React.
It ships out of the box with lots of components like Button, Modal, Alerts, Form and a host of other useful UI components to make development easy.
Reactstrap does not include support for innate Bootstrap Css Javascript files but provides the necessary props to handle dynamic functions.

Is Reactstrap the same as Bootstrap?

No, Reactstrap and Bootstrap CSS are two different UI libraries. Reactstrap is a component library made exclusively for ReactJs while Bootstrap is a popular CSS framework for building and designing websites.

It relies heavily on Javascript which manipulates the DOM to trigger component functionalities.

Although Reactstrap makes use of Bootstrap CSS classes behind the scenes for its components, it abstracts these classes and provides appropriate props that you can use to make components dynamic.

Difference between Reactstrap and React Bootstrap

Reactstrap React Bootstrap
It is a component library for Reactjs It is a library that provides a set of reusable React components based on Bootstrap CSS framework
Created 7 years ago Created 9 years ago
Has less downloads Has more downloads
Has over 10.4k stars on github Has over 21.2k stars on Github

Which is better Reactstrap or react-Bootstrap?

Both Reactstrap and react-Bootstrap are great component libraries with lots of pre-built bootstrap-based components that you can start using rapidly in your react applications.

Choosing between the two will be kind of subjective to the developer. Reactstrap is easy to use and customize. It also gets frequent updates and a large community of maintainers.
Reactstrap is an excellent option if you’re looking for a quick way to add Bootstrap components to your React app.

React Bootstrap on the other hand has been in the business for quite longer than reactstrap so it's logical that it would garner more popularity than Reactstrap with over 21k stars and 400+ contributors. To learn more about React Bootstrap, you can watch this video by Adrain.

Setting up a React App using NPM and Yarn

  • Let's create react app by going to a directory on your computer and typing:

mkdir reactstrap-app

  • Then go into the directory

cd reactstrap-app

  • If you are using npm, run:

npx create-react-app .

The "." ensures that the react app is created inside the folder which you just created.

  • For Yarn use:

yarn create react-app .

For the sake of this tutorial, I will be making use of yarn because it's a bit faster than npm for me.

After creating a react app, you should have the below folder structure. You will also notice that react dom and react were installed automatically. You can view this on the package.json file.

Image description

Adding Reactstrap library in React Project

  • Next, let's install reactstrap and bootstrap.

yarn add reactstrap bootstrap

  • Then run:

npm start

  • Or yarn start to start your React app.

  • Next, go to App.js and import bootstrap.min.css to the top of the file

import 'bootstrap/dist/css/bootstrap.min.css';

Alternatively, you can add the bootstrap css framework using a CDN by going to the public folder and locating your index.html file.

  • Paste the following at the beginning of the file.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css"/>
Enter fullscreen mode Exit fullscreen mode

Great, now go back to App.js and create your first reactstrap component.

  • First, import the button component from reactstrap.

import { Button } from 'reactstrap';

  • Then add it to the App component.
export default function App() {
  return (
    <div>
      <Button> Hello World </Button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode
  • So your App.js should look like so.
import React from 'react';
import './style.css';
import { Button } from 'reactstrap';

export default function App() {
  return (
    <div>
      <Button> Hello World </Button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Building a button counter app

Let's dive into Reactstrap by building out a simple button counter app. The button counter app should look and function like the below after we are through with it.

A counter app in reactjs

We will be needing a couple of components that reactstrap comes with like Button, Container, Row and Col.

  • Go ahead and import them like so.

import { Button, Container, Row, Col } from 'reactstrap';

  • We also be needing to use hooks to set and update our counter variable, so go ahead and do this.

import React, { useState } from 'react';

  • We will set up a useState hook that sets a counter variable and updates it if a button is clicked. Notice that the initial value of counter is set to 0.

const [counter, setCounter] = useState(0);

  • Next, add the below code to your App component.
 return (
    <div>
      <Container className="bg-light py-4 mt-4">
        <Row className="text-center">
          <Col className="mb-1" xs="12">
            The current count is: {counter}
          </Col>
          <Col xs="12">
            <Button> Click me </Button>
          </Col>
        </Row>
      </Container>
    </div>
  );
Enter fullscreen mode Exit fullscreen mode

Here, we are basically using the reactstrap Container component to hold our UI while adding a couple of bootstrap CSS utility classes like paddings and margins. We also centre-aligned the contents of the Row component so everything gets centered neatly.

A quick reminder that you can be able to apply bootstrap CSS class names directly on reactstrap components since reactstrap uses Bootstrap styles behind the scenes.
Here is a cheat sheet containing almost all bootstrap classes. You can use this as a reference file to quickly look up specific styles and class names to style your components however you deem fit.

  • Great, now lets create a function to handle when we click the button.
  const handleClick = () => {
    setCounter(() => counter + 1);
  };
Enter fullscreen mode Exit fullscreen mode

Here, we are updating the setCounter method to an increment of counter variable.

  • Next, let's hook it up to the button.

<Button onClick={handleClick}> Click me </Button>

  • And we are done with it. Here is the full code below.
import React, { useState } from 'react';
import './style.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Button, Container, Row, Col } from 'reactstrap';

export default function App() {
  const [counter, setCounter] = useState(0);

  const handleClick = () => {
    setCounter(() => counter + 1);
  };

  return (
    <div>
      <Container className="bg-light py-4 mt-4">
        <Row className="text-center">
          <Col className="mb-1" xs="12">
            The current count is: {counter}
          </Col>
          <Col xs="12">
            <Button onClick={handleClick}> Click me </Button>
          </Col>
        </Row>
      </Container>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Building a basic blog web app with the Reactstrap component library

From the above sample, we learnt how to use some basic components like Button, Col, Container and so on. Let's take it a little further and cover some other useful components by building a simple news or blog web application with reactstrap.

We will be using Rapid API to get all the news data that we will need and render them using react.

Rapid API is a web service that offers more than 10,000 APIs covering several niches and ecosystems such as Travel, Covid-19 stats, Sports, Movies, Entertainment and so on.

  • We will be using one of their news API to build this app. So go ahead and visit the website using this link. You can sign up using Google, GitHub or Facebook accounts if you are currently signed in to any of those.

rapid api home page

  • Next, go to the search bar at the top and type "Crypto News Live". This will be the API service we will be using to build a news reactstrap app.

Crypto news api
You will be needing to subscribe to the API service to get access. There is a freemium plan that you can use. The only limitation is that there is a cap on the amount of requests you can make to the API.

Rapid api
This usually differs from one API service provider to another. For the most part, the basic version will be enough for this little project.

  • Click on subscribe to get access to call the API.

  • Head back to the endpoints tab. Here you can see all endpoints that is available for use and the necessary API keys that are auto generated for you.

  • You can hit the test endpoints button to test the response gotten from making a request to the API.

  • On the far right are already-made code snippets for virtually the most popular languages like JavaScript, Java, Go, Python e.t.c

Building the navigation

Also, create a component folder on your root folder. This will be where we will store all the necessary components relevant to this app.
You can use the command line to quickly do this by using:

mkdir components
cd components
Enter fullscreen mode Exit fullscreen mode
  • Let's add a reactstrap navigation bar to give our app a decent look and feel. Copy and paste the code below.
import React, { useState } from 'react';
import {
  Collapse,
  Navbar,
  NavbarToggler,
  NavbarBrand,
  Nav,
  NavItem,
  NavLink,
} from 'reactstrap';

const Navigation = (args) => {
  const [isOpen, setIsOpen] = useState(false);

  const toggle = () => setIsOpen(!isOpen);

  return (
    <div>
      <Navbar {...args}>
        <NavbarBrand href="/">Newsly</NavbarBrand>
        <NavbarToggler onClick={toggle} style={{ fontSize: 16 }} />
        <Collapse isOpen={isOpen} navbar>
          <Nav className="me-auto" navbar>
            <NavItem>
              <NavLink href="/latest">Latest</NavLink>
            </NavItem>
          </Nav>
        </Collapse>
      </Navbar>
    </div>
  );
};

export default Navigation;

Enter fullscreen mode Exit fullscreen mode

We are doing a couple of things here, and if you are conversant with the Bootstrap css framework some of these names may sound familiar to you. The Navbar brand component works like the Bootstrap CSS navbar-brand class. This is where you insert your company, project or application's name. In our own case, we will call it Newsly.

The NavbarToggler component is used to trigger the show and hide functionality of the navigation. We added a font-size of 16 to reduce the size of the button that comes out of the box with it.

Lastly, the Collapse component is used to show or hide the nav items depending on the current state isOpen.

Adding a Loading indicator with reactstrap

Like Bootstrap Css, reactstrap component library contains lots useful components like Spinners that can help indicate the state of the project.

  • Go to your components folder and create a new file named Loader.js and add the below code.
import React from 'react';
import { Spinner } from 'reactstrap';

const Loader = () => {
  return (
    <div
      style={{
        display: 'flex',
        justifyContent: 'center',
      }}
    >
      <Spinner
        color="primary"
        style={{
          height: '3rem',
          width: '3rem',
        }}
      ></Spinner>
    </div>
  );
};

export default Loader;
Enter fullscreen mode Exit fullscreen mode

We are simply importing the Spinner Component from reactstrap and adding some css to justify it to the centre of the screen.

Adding a NewsCard

  • Next, lets build a news card to show all the recent news from the API.
import React from 'react';
import { Card, CardBody, CardTitle, Button, CardText } from 'reactstrap';

const NewsCard = (props) => {
  return (
    <Card
      color="light"
      style={{
        width: '18rem',
      }}
    >
      <img
        alt="A random image"
        src= {props.image}
      />
      <CardBody>
        <CardTitle tag="h6">{props.title.substr(0, 55)}...</CardTitle>
        <CardText>
          This news was curated from <a href={props.source}>{props.source}</a>
        </CardText>
        <Button href={props.url}>Visit</Button>
      </CardBody>
    </Card>
  );
};

export default NewsCard;
Enter fullscreen mode Exit fullscreen mode

Here we are importing the Card, CardBody, CardTitle, Button, CardText from reactstrap and adding a couple of styles to it to make it look decent.

{props.title.substr(0, 55)}

For the Card title, we are getting and displaying the first 55 characters so that the card will have a consistent title character number.

Building the Layout

We'll make use of the several layout components in reactstrap to build a responsive layout to render our card.

  • We will import all the necessary components that we will needing, both the Loader and NewsCard components that we created before.
import React, { useState, useEffect } from 'react';
import { Row, Col, Container } from 'reactstrap';
import NewsCard from './NewsCard';
import Loader from './Loader';
Enter fullscreen mode Exit fullscreen mode
  • Then create the Layout component and render the news card for now. We also create a placeholder image gotten from pixabay to serve as the CardImage.
const Layout = () => {
  const [newsData, setNewsData] = useState();
    const img =
    'https://cdn.pixabay.com/photo/2022/09/24/15/39/rocks-7476616_960_720.jpg';
  return (
    <>
    <NewsCard />
    </>
  );
};
export default Layout;
Enter fullscreen mode Exit fullscreen mode
  • Next, lets fetch the news API data from Rapid API. You can copy and paste the code snippet from the Endpoints tab.
  const fetchApi = () => {
    const options = {
      method: 'GET',
      headers: {
        'X-RapidAPI-Key': 'your key',
        'X-RapidAPI-Host': 'crypto-news-live3.p.rapidapi.com',
      },
    };

    fetch('https://crypto-news-live3.p.rapidapi.com/news', options)
      .then((response) => response.json())
      .then((data) => {
    console.log(data)
        setNewsData(data);
      })
      .catch((err) => console.error(err));
  };

Enter fullscreen mode Exit fullscreen mode

We just made a basic GET request to the endpoint with fetch api, retrieved the data, console logged it, and add it to a state.

  • Next, lets add a useEffect to fetch data and after any updates.
 useEffect(() => {
    fetchApi();
  }, []);
Enter fullscreen mode Exit fullscreen mode
  • Then add the content layout for the app main body.
  return (
    <>
      {newsData ? (
        <Container>
          <Row>
            {newsData?.slice(0, 12).map((news, index) => (
              <Col
                sm="12"
                lg="4"
                md="6"
                key={index}
              >
                <NewsCard
                  title={news.title}
                  source={news.source}
                  url={news.url}
                  image={undefined ?? img}
                />
              </Col>
            ))}
          </Row>
        </Container>
      ) : (
        <Loader />
      )}
    </>
Enter fullscreen mode Exit fullscreen mode

We are simply mapping through the first 12 data elements from the API and passing each value of the news data object as a prop to the newscard. The Container component adds some paddings and margins to our overall layout.

The loader component will be shown if newData variable is not yet updated.

The complete code looks like this:

import React, { useState, useEffect } from 'react';
import { Row, Col, Container } from 'reactstrap';
import NewsCard from './NewsCard';
import Loader from './Loader';

const Layout = () => {
  const [newsData, setNewsData] = useState();
  const img =
    'https://cdn.pixabay.com/photo/2022/09/24/15/39/rocks-7476616_960_720.jpg';

  useEffect(() => {
    fetchApi();
  }, []);

  console.log(newsData?.[2]);
  const fetchApi = () => {
    const options = {
      method: 'GET',
      headers: {
        'X-RapidAPI-Key': 'your key',
        'X-RapidAPI-Host': 'crypto-news-live3.p.rapidapi.com',
      },
    };

    fetch('https://crypto-news-live3.p.rapidapi.com/news', options)
      .then((response) => response.json())
      .then((data) => {
        setNewsData(data);
      })
      .catch((err) => console.error(err));
  };
  // fetchApi()

  return (
    <>
      {newsData ? (
        <Container>
          <Row>
            {newsData?.slice(0, 12).map((news, index) => (
              <Col
                sm="12"
                lg="4"
                md="6"
                key={index}
              >
                <NewsCard
                  title={news.title}
                  source={news.source}
                  url={news.url}
                  image={undefined ?? img}
                />
              </Col>
            ))}
          </Row>
        </Container>
      ) : (
        <Loader />
      )}
    </>
  );
};
export default Layout;

Enter fullscreen mode Exit fullscreen mode

PS: It is not recommended to leave API keys on your Layout.js file. It is pertinent that you use dotenv a javascript package to handle sensitive data such as API keys. You can read more on this here.

Don't also forget to add .env to your gitignore files when pushing to a remote repository like Github.

  • Now go to your src > App.js and import the Navigation and Layout components. You can comment out the counter app code that we built earlier.
import Layout from './components/Layout';
import Navigation from './components/Navigation';

Enter fullscreen mode Exit fullscreen mode
  • Then render the components.
 return (
    <div>
      <Navigation />
      <Layout />
      {/* <Container className="bg-light py-4 mt-4">
        <Row className="text-center">
          <Col className="mb-1" xs="12">
            The current count is: {counter}
          </Col>
          <Col xs="12">
            <Button onClick={handleClick}> Click me </Button>
          </Col>
        </Row>
      </Container> */}
    </div>
  );

Enter fullscreen mode Exit fullscreen mode

Adding responsiveness

Lets add some margin and responsiveness to the reactstrap app.

  • Go to the styles.css and add the below code.
h1,
p {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
    Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.container {
  margin-top: 40px;
}
div.col-lg-4 {
  margin-bottom: 10px;
}
@media only screen and (max-width: 768px) {
  div.col-md-6 {
    margin-bottom: 10px;
  }
  div.card {
    margin: auto;
  }
}

Enter fullscreen mode Exit fullscreen mode
  • Don't forget to add your styles to scr > app.js
import './style.css';
Enter fullscreen mode Exit fullscreen mode

Conclusion

Great, we were finally able to make use of the plethora of reactstrap components like Spinner, Button, Layout and a host of others. There are more to it as this is just a tip of the iceberg. I recommend you go through reactstrap official documentation to get a feel of the numerous other UIs that they provide.

Top comments (0)