How to Create Dashboard in React

Explore the intricacies of creating a powerful dashboard using React with our comprehensive guide

A quick start guide on building a dashboard using databrain with react

Connect to Your MongoDB Database and Create a Dashboard

Databrain offers support for a range of databases, including Redshift, Postgres, MySQL, Snowflake, and more. 

In this guide, we'll focus on MongoDB as the database of choice, and we'll walk you through the process step by step. 

Let's begin.

Step 1: Connect to Your MongoDB Database

Before connecting to a database, you need to activate the mongoDB instance. 

When you activate the MongoDB BI Connector, it serves as an interface connecting MongoDB and databrain. 

Activating the instance will  make it easier to understand and use your MongoDB information for smarter decision-making.

Now that is done, we can proceed to connect to the database as below - 

  • Log in to DataBrain - https://app.usedatabrain.com/  and go to the "Data Sources" section.
  • Click the "Add New Datasource" button and select "mongoDB."
  • Choose the database you want to connect to. For example, here the workspace name is "Demo workspace."
  • In the "Name" field, give your connection a descriptive and relevant name for identifying your MongoDB BI Connector source.
  • Specify the host (IP address or domain name) where your MongoDB BI Connector is running.
  • Set the port (usually 3306, but check your configuration).
  • Enter the username and password for your MongoDB cluster.

Step 2: Create a Dashboard

  • Click the "Create New Workspace" button (with a plus icon) in the top right corner.
  • Enter the workspace name and description, then click "Save" to create a workspace.
  • Click "Create a New Dashboard."
  • Fill in the dashboard name and a unique dashboard ID, which you'll use later for integration.

Step 3: Design a Metric

  • Click "Create Metric" in the top right corner.
  • Select the dataset and drag and drop data into rows and columns. For example, choose "Public" > "Users'' and select "id," "real_name," and "tz" for columns. 

Choose the chart type (e.g., table) and you can do something similar.

Create as many metrics as you need by using the simple process shown above. 

Integrating with Your App

Step 4: Create a React App

  • Run `npx create-react-app my-app`. This will create the files required for the react app. 
  • After removing the unnecessary files from your react app, this folder structure will look like this - 
  • Remove all the code from app.css.
  • Remove the header part from the app.js
  • Now the react app is clean and organized, let’s install the DataBrain package using `npm install @databrainhq/plugin`.
  • Import it at the top of your React app (usually in App.js or index.js). Here, imported in the app.js file. 

Step 5: Integrate DataBrain

  • To integrate the databrain to your react app you can use the following syntax 

For a dashboard: 

  • A dashboard consists of various metrics put together. 
  • To integrate the entire dashboard, you can paste the following piece of code in the required component. 

              <dbn-dashboard token="token" dashboard-id="dashboardId" />

  • The token and dashboard id can be obtained from the share button.
  • The share button can be located just to the left of the "Create Metric" button.
  • Replace "token" and dashboard id  respectively. 

The Code:

To integrate the dashboard in the react app, insert the below code. 


import "@databrainhq/plugin/web";
        import "./App.css";

        function App() {
            return (
                <div>
                    <dbn-dashboard
                        token="d6862d6e-758e-4d7a-8d2a-8cecf8c5e9b6"
                        dashboard-id="react-dashboard"
                    />
                </div>
            )
        }

        export default App;

Here, we are in the app.js file. 

We have imported the databrain package - import "@databrainhq/plugin/web";

In the app component, we have placed the 'dbn-dashboard' component with actual values of token and dashboard id from the share menu. 

After this, run npm start and you will see the dashboard live and running in your browser

For a metric: 

  • A metric is nothing but an individual piece, a chart, or a data on the dashboard.  
  • But if you choose to integrate only a metric or two, you can use the below code. 

              `<dbn-metric token="token" metric-id="metricId" />`.

  • When you save a metric to the dashboard, you need to fill the metric id. 
  • Use that metric id along with the token obtained from the share menu as shown above. 

The code to integrate the metric is similar to the dashboard above, but with a small change of metric id instead of dashboard.  

After creating a few metrics and integrating with the react app, the dashboard looks like - 

Step 6: Customize Your Dashboard

Once you've integrated DataBrain into your React app and have your dashboard set up, you can customize the dashboard to fit your needs. 

Here's how to do it:

1. Customize Layout : You can arrange the metrics and components on your dashboard by dragging and dropping them. 

You can also resize and rearrange them to create a visually appealing layout.

2. Add Metrics : To add metrics, click on the "Add Metric" button, and select the dataset and data points you want to display. 

You can choose different chart types, like tables, charts, or graphs, based on your data and visualization preferences.

3. Data Filtering : You can add filters to the metrics to allow users to interact with the data dynamically. 

These filters can be based on various attributes or dimensions of your data.

4. Styling : Customize the styling of your dashboard to match your branding or design preferences. 

You can change colors, fonts, and other design elements to make the dashboard visually appealing. 

5. Interactivity : Set up interactions between different components on your dashboard. 

For example, you can create drill-downs, tooltips, or pop-ups to provide more information when users interact with the dashboard.

Step 7: Publish

Once you've customized your dashboard to your satisfaction, it's time to publish it for others to access.

1. Click on the "Publish" or "Save" button to save your changes and make the dashboard live.

2. You can share the URL or embed code for the dashboard with your intended audience or users.

3. Users can access the dashboard from a web browser or through your integrated React app by using the provided token and dashboard ID.

Remember to maintain your dashboard and keep it updated as your data changes or your requirements evolve. 

You can always go back to DataBrain to edit and enhance your dashboard as needed.

This concludes the guide for connecting to your MongoDB database, crafting a dashboard, integrating it with your React app, personalizing and sharing the dashboard.

Note: To display the Databrain dashboard correctly on your website, you need to whitelist your domain.

Here's how to do it:

  1. Go to the 'Settings' section.
  2. Find 'Embed Settings' and click on it.
  3. Select 'Whitelist Domains.'
  4. Paste your website's domain into the 'Allowed Origins' field.
  5. Click the 'Add' button.

By following these steps, you'll ensure that the dashboard integrates seamlessly with your React app."

Create a React App:

Run the following command in your terminal: npx create-react-app my-app.

This command sets up a new React application called "my-app" and generates all the necessary files and folder structure for you.

Clean Up App.js and App.css:

In your project folder, you'll find two important files: App.js and App.css.

These files contain initial code for your React application. You should remove any code that you don't need to keep your project clean and organized.

Install Bootstrap:

To use Bootstrap in your React app, you can install it by running: npm install bootstrap.

This command downloads and adds the Bootstrap library to your project, allowing you to easily style your components.

Create a Components Folder:

To keep your project organized, create a folder named "components" inside the "src" folder.

This "components" folder will house all the custom React components you'll create for your app.

Create a Navbar Component:

Inside the "components" folder, create a sub-folder named "Navbar."

In the "Navbar" folder, create two files: index.js and index.css.

The index.js file will hold the JavaScript code for your Navbar component, while the index.css file will contain the styling for the Navbar.

Each component follows the same structure for uniformity across the code. 

Each component has two files: index.js and index.css. This helps keep things organized and easy to work with, making it clear where the component's code and styling can be found.

Copy this code in the src/components/Navbar/index.js

    
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import "./index.css"

const VerticalNavbar = () => {
    return (
        <nav className="navbar navbar-expand-lg navbar-light ">
            <ul className="navbar-nav d-flex flex-column">
                <li className="nav-item"><a className="nav-link" href="#">Dashboard</a></li>
                <li className="nav-item"><a className="nav-link" href="#">My Courses</a></li>
                <li className="nav-item"><a className="nav-link" href="#">Messages</a></li>
                <li className="nav-item"><a className="nav-link" href="#">Reports</a></li>
                <li className="nav-item"><a className="nav-link" href="#">Settings</a></li>
            </ul>
        </nav>
    );
};

export default VerticalNavbar;
    


Copy this code in src/components/Navbar/index.css 

    
nav {
background-color: #0096ff;
color: white;
width: 60%;
height: 100vh;
max-width: 200px;
font-size: 20px;
}


.navbar-nav .nav-item {
padding: 0 30px;
}


.navbar-nav .nav-item:hover {
background-color: white;
border-radius: 8px;
}


.navbar-nav .nav-item:hover a {
color: #0096ff;
}


.navbar-nav .nav-item a {
color: white;
}

    


The Navbar will look like this:

Install fontawesome Icons:

Run the following command to install the font awesome icons:

npm install --save @fortawesome/react-fontawesome @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons

npm install --save @fortawesome/react-fontawesome: This installs the React Font Awesome library, enabling the use of Font Awesome icons within your React components.

npm install --save @fortawesome/fontawesome-svg-core: This installs the core engine that powers the Font Awesome icon library.

npm install --save @fortawesome/free-solid-svg-icons: This downloads a collection of free, solid-style icons from Font Awesome.

Once you have installed the Font Awesome packages, you can proceed to use the icons in your project. Here's how:

Import the required icons at the top of your React component file:

javascript

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import { faCoffee } from '@fortawesome/free-solid-svg-icons';

In this example, we import the faCoffee icon from the free-solid-svg-icons collection. You can import additional icons as needed.

Within your component's JSX code, use the FontAwesomeIcon component to display the icon:

javascript

<FontAwesomeIcon icon={faCoffee} />

The above explanation can be put into practice in the Header component below. 

Header Component:

Copy this code into the src/components/Header/index.js file

    
<style>
    pre {
        white-space: pre;
        display: block;
        background-color: black;
        padding: 10px;
        border-radius: 8px;
        overflow: auto; /* Enable both horizontal and vertical scrolling */
        max-height: 500px; /* Set a maximum height for vertical scrolling */
    }
</style>

<pre>
    <code>
        import React from 'react';
        import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
        import { faBell } from '@fortawesome/free-solid-svg-icons';
        import "./index.css"

        const Header = () => {
            return (
                <div className="container-fluid bg-light ">
                    <div className="row py-3 d-flex align-items-center mb-3 shadow">
                        <div className="col-6 d-flex ">
                            <div className="input-group rounded-pill">
                                <input type="text" className="form-control rounded-pill" placeholder="Search" />
                                <span className="input-group-text border-0 bg-transparent rounded-pill"></span>
                            </div>
                        </div>
                        <div className="col-6 d-flex justify-content-end align-items-center gap-3">
                            <div className="rounded-circle overflow-hidden">
                                {/* Your profile photo */}
                                <img src="https://img.freepik.com/free-vector/isolated-young-handsome-man-different-poses-white-background-illustration_632498-859.jpg?w=740&t=st=1694269159~exp=1694269759~hmac=c8c65095b670091331a550b674305943e6a42c710a45b7356ecfe851d77b916b" alt="Profile" className="img-fluid profile" />
                            </div>
                            <div className="ml-2 bell-icon">
                                <FontAwesomeIcon icon={faBell} />
                            </div>
                        </div>
                    </div>
                </div>
            );
        };

        export default Header;
    </code>
</pre>

Copy this code into src/components/Header/index.css

    

.profile {
width: 30px;
height: 30px;
}


.bell-icon {
font-size: 20px;
}


    

This code defines a React functional component called `Header`, creating a header section with a search input field, a profile image, and a notification bell icon, styled using Bootstrap classes and custom CSS. 

It also imports and uses Font Awesome for displaying the bell icon.

Courses Component:

Copy this code into src/components/Courses/index.js

    
        import React from 'react'
        import "./index.css"


        const Courses = (props) => {
            const { each } = props
            const { total, text, color } = each
            const colorText = {
                color: `${color}`
            }
            return (
                <div className='d-flex flex-column align-items-center shadow course-container'>
                    <p className='fs-2' style={colorText}>{total} </p>
                    <p>{text} </p>
                </div>
            )
        }

        export default Courses
        
        

Copy this code into src/components/Courses/index.css

    

.course-container {padding: 15px 20px;border-radius: 16px;background-color: white;}

    

In the above code, the color information is dynamically passed down from the parent "body" component through the "courseDetails" array and is subsequently applied to style the text within the "Courses" component. 

This approach allows for adaptable and flexible color rendering based on the provided data.

Course List:

Copy this code into src/components/Courselist/index.js

    
        import React from 'react';
        import "./index.css"


        const courseData = [
            {
                title: 'Web Design',
                level: 'Advance',
                date: '2nd Jan 2023',
                status: 'Completed'
            },
            {
                title: 'React',
                level: 'Advance',
                date: '9th April 2023',
                status: 'On Going',
            },
            {
                title: 'MongoDB',
                level: 'Advance',
                date: '5th June 2023',
                status: 'Interested',
            },
            {
                title: 'Angular',
                level: 'Beginner',
                date: '7th July 2023',
                status: 'Interested',
            },
            {
                title: 'CSS',
                level: 'Intermediate',
                date: '2nd Feb 2023',
                status: 'Completed',
            },
        ];

        const CourseList = () => {
            const textColor = courseData.map(each => {
                if (each.status === "Completed") {
                    return 'green';
                } else if (each.status === 'On Going') {
                    return 'orange';
                } else {
                    return 'blue';
                }
            });

            return (
                <div className="shadow mx-1 px-3 bg-light rounded-3 ">
                    <div className=' d-flex align-items-center justify-content-between p-3 mt-3 ' >
                        <h4 className="mb-0">My Courses</h4>
                        <button className="btn ">See All</button>
                    </div>

                    <div className=' '>
                        <table className="table ">
                            <thead>
                                <tr>
                                    <th>Course Name</th>
                                    <th>Level</th>
                                    <th>Date</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                {courseData.map((course, index) => (
                                    <tr key={index}>
                                        <td>{course.title}</td>
                                        <td>{course.level}</td>
                                        <td>{course.date}</td>
                                        <td style={{ color: textColor[index] }}>{course.status}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            );
        };

        export default CourseList;

    


This code defines a React component named `CourseList` that displays a list of courses. 

It uses an array called `courseData` to hold information about each course, such as the title, level, date, and status. 

The status text color is dynamically determined based on the course's completion status, and the list is presented in a table format. 

Test Schedule Component

Copy this code into src/components/TestSchedule/index.js

    

        import React from 'react';
        import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
        import { faCode } from '@fortawesome/free-solid-svg-icons';
        import "./index.css"


        const TestScheduleComponent = () => {
            const testItems = [
                {
                    title: 'React Test ',
                    description: 'Jan 2nd 2023, 2pm to 4pm',
                },
                {
                    title: 'Web Design Test ',
                    description: '5th Jan 2023, 10am to 12pm',
                },
                {
                    title: 'CSS Test ',
                    description: '8th Jan 2023, 2pm to 4pm ',
                },
                {
                    title: 'MongoDB',
                    description: '12th Jan 2023, 10am to 12pm',
                },
            ];

            return (
                <div className='shadow bg-light p-3 h-100'>
                    <h5 className='fw-bold'>Test Schedule</h5>
                    {testItems.map((item, index) => (
                        <div key={index} className="test-div row d-flex align-items-center">
                            <div className="col-md-4">
                                <FontAwesomeIcon icon={faCode} />
                            </div>
                            <div className="col-md-8">
                                <p>{item.title}</p>
                                <p className="test_details">{item.description}</p>
                            </div>
                        </div>
                    ))}
                    <hr />
                    <div className="text-center">
                        <button className="btn btn-primary">See All</button>
                    </div>
                </div>
            );
        };

        export default TestScheduleComponent;
        
        

Now we have all the components needed for this dashboard. All we have to do is put them together in the Body component as below:

Body Component

Copy this code into src/components/Body/index.js

    

import React from 'react'
        import Header from '../Header'
        import Courses from '../Courses'
        import CourseList from '../Courselist'
        import "./index.css"
        import TestSchedule from '../TestSchedule'

        const courseDetails = [
            { id: 1, total: 2, text: 'Current Courses ', color: 'orange' },
            { id: 2, total: 5, text: 'Completed Courses', color: 'green', },
            { id: 3, total: 10, text: "Interested Courses", color: 'blue' },
        ];

        const Body = () => {
            return (
                <div className='w-100 course-wrapper'>
                    <Header />
                    <h4 className='mx-3 d-block'>Welcome Back, John</h4>
                    <div className='d-flex justify-content-around'>
                        <div>
                            <div className='d-flex gap-5 mt-4 '>
                                {courseDetails.map(each => (
                                    <Courses key={each.id} each={each} />
                                ))}
                            </div>
                            <div>
                                <CourseList />
                            </div>
                        </div>
                        <TestSchedule />
                    </div>
                </div>
            );
        };

        export default Body;

    

Copy this code into src/components/Body/index.css

    
.course-wrapper {background-color: lightblue;}

    


The courseDetails array holds information about different course categories, such as "Current Courses," "Completed Courses," and "Interested Courses," with associated colors.

Within the component, there's a structured layout:

  • A header (imported from Header.js) at the top.
  • A personalized greeting message for the user.
  • A display of course categories with counts and colors.
  • A list of courses (imported from Courses.js), including their titles and status icons.
  • A section displaying test schedules (imported from TestSchedule.js).
  • The background of the entire content area is styled with a light blue color.

Also, we have made the Courses component reusable as below:

Rendering React Components:

For each element (referred to as each) in the courseDetails array, the code does the following:

It renders a React component called Courses.

The key attribute is set to each.id. This key is used by React to keep track of individual elements in a list and optimize rendering.

Each object, representing a course, is passed as a prop to the Courses component using each={each}.

The App Component:

Copy this code into src/app.js

import './App.css'; import VerticalNavbar from './components/Navbar'; import Body from './components/Body'; function App() { return ( <div className='d-flex '> <VerticalNavbar /> <Body /> </div> ); } export default App;

Copy this code into src/app.css

    

* {margin: 0;padding: 0;box-sizing: border-box;}

    

The Project Structure:

After setting up all the components the project structure will look like this:

Final Steps:

We've assembled all the components, and now it's time to launch the live dashboard by running 'npm start'.

The dashboard will look like this:

Hope you enjoyed this tutorial. See you in the next one!

Make customer facing analytics your competitive advantage