How to Create an Online Real-Time Bidding/Auction App
Published: 2024-02-22 15:03:11

In this tutorial, we'll show you how to build a user-friendly online auction application in React using [PubNub Real-time Messaging](https://www.pubnub.com/products/pubnub-platform/) and React-Bootstrap. The auction app will have a gallery of artwork and you can join the bidding event to place bids on the art. While placing your bids, you can simultaneously check the bids placed by other users in real time. Your app will also have a dashboard that can be used by the admin to track the viewers and their bids.

Use cases for a bidding app
---------------------------

Some great ideas for an auction or bidding app are:

-   Selling collectibles
    
-   Selling everyday items
    
-   Using it to sell clothing and luxury clothing items
    
-   Create auctions for art pieces
    
-   Real-estate
    
-   In-app purchases
    
-    And more!
    

Examples of online auction apps

-   [_Ebay_](https://www.ebay.com/)
    
-   [_Kijiji_](https://www.kijiji.ca/)
    

**Why use React to build an auction app?**
------------------------------------------

[React](https://reactjs.org/) is a JavaScript library for building user interfaces. React gives you a template language and some function hooks to render HTML. Your bundles of HTML/JavaScript are called "components".

Components are similar to JavaScript functions. They accept arbitrary inputs called props and return React elements. These elements describe what should appear on the screen for your bidding platform.

Developers love ReactJS because it is highly performant and render changes almost instantly. The best part about ReactJS is that it is a relatively small framework and does not take too much time to learn!

**How to create your bidding app**
----------------------------------

**The** [**full GitHub code repository can be found here**](https://github.com/namrathasubramanya/reactjs-bidding-dashboard)**.** To get started with your auction platform, first, you’ll have to [sign up for a PubNub account](https://dashboard.pubnub.com/signup) to get your unique publish/subscribe keys. Then, install PubNub package using the following command in your terminal. PubNub's real-time infrastructure simplifies the bidding process, ensuring a smooth user experience. Begin by installing the PubNub package in your project:

```js
npm install --save pubnub pubnub-react
```

Import the required libraries.

```js
import PubNub from 'pubnub';
import { PubNubProvider, usePubNub } from 'pubnub-react';
import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import PropTypes from 'prop-types'
```

The PubNub React Framework is a wrapper of PubNub Javascript. It adds a few extra features to simplify the integration with React. In order to get the integration between your React Components and PubNub, `pubnub-react` will be the way to get this without any kind of difficulty or extra job when you need to render data in your UI.

Here is how you can initialize PubNub in your application which will be providing the authentication system ensuring secure communication across your bidding system.

```js
const pubnub = new PubNub({
  publishKey: 'myPublishKey',
  subscribeKey: 'mySubscribeKey',
  uuid: 'myUniqueUUID'
});

function App() {
  return (
    <PubNubProvider client={pubnub}>
      <Chat />
    </PubNubProvider>
  );
}
```

Let's divide the application into Bidding Portal and Admin Dashboard. The bidding portal would be used by customers to bid prices during an auction. And the dashboard can be used by the admins to track values of the auction.

**Creating the Bidding Portal for your auction app**
----------------------------------------------------

### **Creating Registration for your auction**

Let's have a registration modal to register the user. Make the registration mandatory. This way, you can keep track of every bid that comes in from potential buyers.

![](https://www.pubnub.com/cdn/3prze68gbwl1/asset-17suaysk1qa1j7c/ce6facfb5ae3fe555b2cfd73af9a8dbe/Screen-Shot-2018-07-05-at-2.14.07-PM.png)

Inside `render()`:

```js
<form onSubmit={this.handleSubmit}>
   <ModalHeader>Live Bidding Registration</ModalHeader>
      <ModalBody>
         <label>Name:</label>
         <input type="text" value={this.state.name} onChange={this.handleChangeName} className="form-control" />  
      </ModalBody>
      <ModalFooter>
         <Button type="submit" onClick={this.handleSubmit} color="success" className="btn btn-success">Register</Button>
         <Button color="danger" onClick={this.toggle}>Cancel</Button>
      </ModalFooter>
</form>
```

### **How to create a Homepage for your bidding app**

Routing helps us build a single page auction application in React. To use routing, we have to pull down React Router and React DOM:

```js
npm install react-router-dom --save
```

This is how you can build a single page bidding application using routers by switching between the tabs.

```js
<main>
   <Switch>
      <Route exact path='/' component={Home}/>
      <Route path='/products' component={Products}/>
      <Route path='/contact' component={Contact}/>
      <Route path='/art' component={Art}/>
      <Route path='/about' component={About}/>
      <Route path='/user' component={User}/>
      <Route path='/dashboard' component={Dashboard}/>
    </Switch> 
</main>
```

### **Using Products – PubNub Channels in your bidding app**

Products here represent different channels of PubNub in your live auction app. You can re-use React components in such a way that the buttons on different art products lead you to different channels.

![](https://www.pubnub.com/cdn/3prze68gbwl1/asset-17suaysk1qa1j7d/53c01292fc14d47514c92b7f96a4313b/Screen-Shot-2018-07-05-at-2.10.12-PM.png)

The Cardholder component receives values passed by the

tag in the products page.

```js
<Cardholder name="Art 1" description="Description of Art 1" image={image9}/>
```

Here's a small code snippet of Cardholder, which can be used to build a number of products by passing different product names and their associated subtitles and description. Additionally, you can make the buttons lead you to different PubNub channels based on the product.

```js
<Card>
   <CardImg top width="10%" src={this.props.image} alt="Card image cap" />
   <CardBody>
       <CardTitle><h1>{this.props.name}</h1></CardTitle>
       <CardSubtitle>Card subtitle</CardSubtitle>
       <CardText>{this.props.description}</CardText>
       <Route render={({ history}) => (
           <Button className="btn btn-info" onClick={() => { history.push(channelName) }}>
                Join the event
           </Button>
       )} />
    </CardBody>
</Card>
```

### Placing a Bid

![](https://www.pubnub.com/cdn/3prze68gbwl1/asset-17suaysk1qa1j7e/715a28fb97d0268bd1f20ed5e7a668db/Screen-Shot-2018-07-05-at-2.13.43-PM.png)

The most interesting part of your auction application is the page where you place the bid. The buttons on the products page lead you to their corresponding PubNub channels, which in turn lead you to the corresponding bidding pages, where you can submit the amount.

```js
  <form onSubmit={this.handleSubmit} style={{marginLeft: 10 + 'em'}}>
      <h2> Starting bid: $30 </h2>
      <label>
         <FormControl type="number" pattern="[0-9]*" inputMode="numeric" value={this.state.value} onChange={this.handleChange} />
      </label>
      <Button className="btn btn-info btn-lg" type="submit" value="Submit" style={{marginLeft: 10 + 'px'}}>Place Bid</Button>
  </form>
```

### **Using PubNub for Real-time Messaging for your bidding app**

```js
function handleSubmit(event) {
   var startingBid = 30;
   var data = localStorage.getItem('Username');
   var message = data +" : "+ this.state.value;
   if(data != null) {
      if(this.state.value > startingBid && this.state.value < 1000000) {
         pubnub.publish({
            message: message,
            channel: 'art'
         });
      } else {
         alert("Enter value between Starting Bid and 1000000!");
      }
   }else {
      alert("Enter username!");
   }
   event.preventDefault();
}
```

**Building a Bidding Dashboard**
--------------------------------

### **Using Presence in your bidding app**

Presence delivers the status of users and devices connected to PubNub's channels at any point under a millisecond. PubNub requires you to enable Presence on their PubNub Dashboard.

[Here's how to enable Presence](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-). Now you can execute this piece of code to find out how many users/devices are connected to a PubNub channel at the moment.

```js
pubnub.hereNow({ 
   channels: ["art"], 
   includeState: true 
},(status,response)=> { 
   this.setState ({ 
      people: response.totalOccupancy 
   }); 
});
```

![](https://www.pubnub.com/cdn/3prze68gbwl1/asset-17suaysk1qa1j7f/66c33d092fafaec2f9161d25eb112908/Screen-Shot-2018-07-05-at-2.15.19-PM.png)

Here is how you can design the Admin Dashboard cards to display the number of bids, highest bid, and the number of viewers. You can also implement graphs and charts to represent these values graphically.

```js
import React, { useState } from 'react';
import { Row, Col, Card, CardBody } from 'reactstrap';
import PropTypes from 'prop-types';

function Cards({ data, highest, people }) {
  // State hooks
  const [collapse, setCollapse] = useState(true);
  const [fadeIn, setFadeIn] = useState(true);

  // Toggle functions using hooks
  const toggle = () => setCollapse(!collapse);
  const toggleFade = () => setFadeIn(prevFadeIn => !prevFadeIn);

  // useEffect can be used if you need to perform side effects, similar to componentDidMount, componentDidUpdate, and componentWillUnmount combined in class components.
  // If needed, you can include useEffect hooks here.

  return (
    <div className="animated fadeIn">
      <Row>
        <Col xs="12" sm="6" md="4">
          <Card className="text-white bg-info card text-center">
            <CardBody>
              <blockquote className="card-bodyquote">
                <header>Number of Bids</header>
                <h1>{data}</h1>
              </blockquote>
            </CardBody>
          </Card>
        </Col>
        <Col xs="12" sm="6" md="4">
          <Card className="text-white bg-warning card text-center">
            <CardBody>
              <blockquote className="card-bodyquote">
                <header>Highest bid</header>
                <h1>{highest}</h1>
              </blockquote>
            </CardBody>
          </Card>
        </Col>
        <Col xs="12" sm="6" md="4">
          <Card className="text-white bg-success card text-center">
            <CardBody>
              <blockquote className="card-bodyquote">
                <header>Users online</header>
                <h1>{people}</h1>
              </blockquote>
            </CardBody>
          </Card>
        </Col>
      </Row>
    </div>
  );
}

// PropType validations remain the same
Cards.propTypes = {
  data: PropTypes.string,
  highest: PropTypes.string,
  people: PropTypes.string,
};

export default Cards;
```

**Creating a bidding app: Ideas for Implementation**
----------------------------------------------------

Congratulations! Now you have your small bidding portal. You can have OAuth 2.0 for login instead of username modal and you can design the dashboard using CSS to display statistics of multiple artwork. You can also add payment gateways and reserve price functionality to your application allowing users to make transactions within your online auction platform.

See how else PubNub can help add features to your auction software.

1.  [Mobile Push Notifications](https://www.pubnub.com/docs/push/send): Notify mobile users who are away from the app about any chat messages, project updates, or application updates.
    
2.  [App Context](https://www.pubnub.com/docs/general/metadata/channel-metadata): Store information about your user in one place without setting up or calling your database.
    
3.  [Access Manager](https://www.pubnub.com/docs/security/access-control): Restrict access for private conversations, channel rooms, documents, and projects for specific users.
    
4.  [Functions](https://www.pubnub.com/docs/general/serverless/functions/overview): Translate messages, censor inappropriate messages, announce the arrival of new users, and notify other users of mentions.
    
5.  [Events & Actions](https://www.pubnub.com/docs/general/serverless/events-and-actions/overview): Centrally manage events in your application’s ecosystem and trigger business logic without code.
    

Further Reading
---------------

-   [What is an eCommerce application?](https://www.pubnub.com/learn/glossary/what-is-an-ecommerce-application/)
    
-   [PubNub eCommerce solutions overview](https://www.pubnub.com/solutions/ecommerce/)
    
-   [Real-Time Auction Demo](https://www.pubnub.com/demos/auction/)
    

How can PubNub help you?
========================

This article was originally published on [PubNub.com](https://www.pubnub.com/blog/creating-an-online-realtime-bidding-auction-app/)

Our platform helps developers build, deliver, and manage real-time interactivity for web apps, mobile apps, and IoT devices.

The foundation of our platform is the industry's largest and most scalable real-time edge messaging network. With over 15 points-of-presence worldwide supporting 800 million monthly active users, and 99.999% reliability, you'll never have to worry about outages, concurrency limits, or any latency issues caused by traffic spikes.

Experience PubNub
-----------------

Check out [Live Tour](https://www.pubnub.com/tour/introduction/) to understand the essential concepts behind every PubNub-powered app in less than 5 minutes

Get Setup
---------

Sign up for a [PubNub account](https://admin.pubnub.com/signup/) for immediate access to PubNub keys for free

Get Started
-----------

The [PubNub docs](https://www.pubnub.com/docs) will get you up and running, regardless of your use case or [SDK](https://www.pubnub.com/docs)