PrimeReact UI Component Dock With Menu Item

Introduction

PRIMEREACT UI framework that has Over 80 React UI Components with top-notch quality to help you implement all your UI requirements in style.

Dock is a navigation component consisting of menu items.

Preconditions

  • Javascript
  • Basic knowledge of React js
  • Node.js
  • V.S. Code,Visual Studio

We cover the below things,

  • Create React application
  • Installation of Primeface
  • How to Apply Dock of Primeface in React js

Step 1

npx create-react-app prime-app
cd prime-app
npm start

Step 2

Run the below command  for installing PrimeReact

npm install primereact primeicons

Step 3

Add the below code in the App.js

import 'primeicons/primeicons.css';
import 'primereact/resources/themes/lara-light-indigo/theme.css';
import 'primereact/resources/primereact.css';
import 'primeflex/primeflex.css';
import ReactDOM from 'react-dom';
import React, { useState, useEffect, useRef } from 'react';
import PrimeReact from 'primereact/api';
import { Dock } from 'primereact/dock';
import { Tooltip } from 'primereact/tooltip';
import { Dialog } from 'primereact/dialog';
import { Terminal } from 'primereact/terminal';
import { TerminalService } from 'primereact/terminalservice';
import { Galleria } from 'primereact/galleria';
import { Toast } from 'primereact/toast';
import { Tree } from 'primereact/tree';
import { Menubar } from 'primereact/menubar';
import { NodeService } from './CountryService';
import { PhotoService } from './CountryService';
import './App.css';

function App() {

    const [displayTerminal, setDisplayTerminal] = useState(false);
    const [displayFinder, setDisplayFinder] = useState(false);
    const [images, setImages] = useState(null);
    const [nodes, setNodes] = useState(null);
    const toast = useRef(null);
    const toast2 = useRef(null);
    const galleria = useRef(null);

    const imgPath = 'images/dock';
    const imgErrorPath = 'https://www.primefaces.org/wp-content/uploads/2020/05/placeholder.png';

    const dockItems = [
        {
            label: 'Finder',
            icon: () => <img alt="Finder" src="https://www.primefaces.org/primereact/images/dock/finder.svg" onError={(e) => e.target.src = imgErrorPath} width="100%" />,
            command: () => {
                setDisplayFinder(true);
            }
        },
        {
            label: 'Terminal',
            icon: () => <img alt="Finder" src="https://www.primefaces.org/primereact/images/dock/terminal.svg" onError={(e) => e.target.src = imgErrorPath} width="100%" />,
            command: () => {
                setDisplayTerminal(true);
            }
        },
        {
            label: 'App Store',
            icon: () => <img alt="App Store" src="https://www.primefaces.org/primereact/images/dock/appstore.svg" onError={(e) => e.target.src = imgErrorPath} width="100%" />,
            command: () => {
                toast2.current.show({ severity: 'error', summary: 'An unexpected error occurred while signing in.', detail: 'UNTRUSTED_CERT_TITLE' });
            }
        },
        {
            label: 'Safari',
            icon: () => <img alt="Finder" src="	https://www.primefaces.org/primereact/images/dock/safari.svg" onError={(e) => e.target.src = imgErrorPath} width="100%" />,
            command: () => {
                toast2.current.show({ severity: 'warn', summary: 'Safari has stopped working' });
            }
        },
        {
            label: 'Photos',
            icon: () => <img alt="Photos" src="https://www.primefaces.org/primereact/images/dock/photos.svg" onError={(e) => e.target.src = imgErrorPath} width="100%" />,
            command: () => {
                galleria.current.show();
            }
        },
        {
            label: 'GitHub',
            icon: () => <img alt="Settings" src="https://www.primefaces.org/primereact/images/dock/github.svg" onError={(e) => e.target.src = imgErrorPath} width="100%" />,
        },
        {
            label: 'Trash',
            icon: () => <img alt="trash" src="https://www.primefaces.org/primereact/images/dock/trash.png" onError={(e) => e.target.src = imgErrorPath} width="100%" />,
            command: () => {
                toast.current.show({ severity: 'info', summary: 'Empty Trash' });
            }
        }
    ];

    const dockBasicItems = [
        {
            label: 'Finder',
            icon: () => <img alt="Finder" src="https://www.primefaces.org/primereact/images/dock/finder.svg" onError={(e) => e.target.src = imgErrorPath} width="100%" />
        },
        {
            label: 'App Store',
            icon: () => <img alt="App Store" src="https://www.primefaces.org/primereact/images/dock/appstore.svg" onError={(e) => e.target.src = imgErrorPath} width="100%" />
        },
        {
            label: 'Photos',
            icon: () => <img alt="Photos" src="https://www.primefaces.org/primereact/images/dock/photos.svg" onError={(e) => e.target.src = imgErrorPath} width="100%" />
        },
        {
            label: 'Trash',
            icon: () => <img alt="trash" src="https://www.primefaces.org/primereact/images/dock/trash.png" onError={(e) => e.target.src = imgErrorPath} width="100%" />
        }
    ];

    const menubarItems = [
        {
            label: 'Finder',
            className: 'menubar-root'
        },
        {
            label: 'File',
            items: [
                {
                    label: 'New',
                    icon: 'pi pi-fw pi-plus',
                    items: [
                        {
                            label: 'Bookmark',
                            icon: 'pi pi-fw pi-bookmark'
                        },
                        {
                            label: 'Video',
                            icon: 'pi pi-fw pi-video'
                        },

                    ]
                },
                {
                    label: 'Delete',
                    icon: 'pi pi-fw pi-trash'
                },
                {
                    separator: true
                },
                {
                    label: 'Export',
                    icon: 'pi pi-fw pi-external-link'
                }
            ]
        },
        {
            label: 'Edit',
            items: [
                {
                    label: 'Left',
                    icon: 'pi pi-fw pi-align-left'
                },
                {
                    label: 'Right',
                    icon: 'pi pi-fw pi-align-right'
                },
                {
                    label: 'Center',
                    icon: 'pi pi-fw pi-align-center'
                },
                {
                    label: 'Justify',
                    icon: 'pi pi-fw pi-align-justify'
                },

            ]
        },
        {
            label: 'Users',
            items: [
                {
                    label: 'New',
                    icon: 'pi pi-fw pi-user-plus',

                },
                {
                    label: 'Delete',
                    icon: 'pi pi-fw pi-user-minus',

                },
                {
                    label: 'Search',
                    icon: 'pi pi-fw pi-users',
                    items: [
                        {
                            label: 'Filter',
                            icon: 'pi pi-fw pi-filter',
                            items: [
                                {
                                    label: 'Print',
                                    icon: 'pi pi-fw pi-print'
                                }
                            ]
                        },
                        {
                            icon: 'pi pi-fw pi-bars',
                            label: 'List'
                        }
                    ]
                }
            ]
        },
        {
            label: 'Events',
            items: [
                {
                    label: 'Edit',
                    icon: 'pi pi-fw pi-pencil',
                    items: [
                        {
                            label: 'Save',
                            icon: 'pi pi-fw pi-calendar-plus'
                        },
                        {
                            label: 'Delete',
                            icon: 'pi pi-fw pi-calendar-minus'
                        }
                    ]
                },
                {
                    label: 'Archieve',
                    icon: 'pi pi-fw pi-calendar-times',
                    items: [
                        {
                            label: 'Remove',
                            icon: 'pi pi-fw pi-calendar-minus'
                        }
                    ]
                }
            ]
        },
        {
            label: 'Quit'
        }
    ];

    const responsiveOptions = [
        {
            breakpoint: '1024px',
            numVisible: 3
        },
        {
            breakpoint: '768px',
            numVisible: 2
        },
        {
            breakpoint: '560px',
            numVisible: 1
        }
    ];

    const itemTemplate = (item) => {
        return <img src={item.itemImageSrc} alt={item.alt} style={{ width: '100%', display: 'block' }} />;
    }

    const commandHandler = (text) => {
        let response;
        let argsIndex = text.indexOf(' ');
        let command = argsIndex !== -1 ? text.substring(0, argsIndex) : text;

        switch (command) {
            case 'date':
                response = 'Today is ' + new Date().toDateString();
                break;

            case 'greet':
                response = 'Hola ' + text.substring(argsIndex + 1) + '!';
                break;

            case 'random':
                response = Math.floor(Math.random() * 100);
                break;

            case 'clear':
                response = null;
                break;

            default:
                response = 'Unknown command: ' + command;
                break;
        }

        if (response) {
            TerminalService.emit('response', response);
        }
        else {
            TerminalService.emit('clear');
        }
    }

    useEffect(() => {
        TerminalService.on('command', commandHandler);

        const nodeService = new NodeService();
        const galleriaService = new PhotoService();

        galleriaService.getImages().then(data => setImages(data));
        nodeService.getTreeNodes().then(data => setNodes(data));

        PrimeReact.appendTo = 'self';

        return () => {
            TerminalService.off('command', commandHandler);

            // reset
            PrimeReact.appendTo = null;
        }
    }, [])

    const start = <i className="pi pi-apple"></i>;
    const end = (
        <React.Fragment>
            <i className="pi pi-video" />
            <i className="pi pi-wifi" />
            <i className="pi pi-volume-up" />
            <span>Fri 13:07</span>
            <i className="pi pi-search" />
            <i className="pi pi-bars" />
        </React.Fragment>
    );


    return (
        <>
        <div className="dock-demo">
            <h5>Basic</h5>
            <div className="dock-window">
                <Dock model={dockBasicItems} position="bottom" />
                <Dock model={dockBasicItems} position="top" />
                <Dock model={dockBasicItems} position="left" />
                <Dock model={dockBasicItems} position="right" />
            </div>

            <h5>Advanced</h5>
            <Tooltip className="dark-tooltip" target=".dock-advanced .p-dock-action" my="center+15 bottom-15" at="center top" showDelay={150} />

            <Menubar model={menubarItems} start={start} end={end} />
            <div className="dock-window dock-advanced">
                <Toast ref={toast} />
                <Toast ref={toast2} position="top-center" />

                <Dock model={dockItems} />

                <Dialog visible={displayTerminal} breakpoints={{ '960px': '50vw' }} style={{ width: '30vw' }} onHide={() => setDisplayTerminal(false)} maximizable blockScroll={false}>
                    <Terminal welcomeMessage="Welcome to PrimeReact (cmd: 'date', 'greet {0}', 'random' and 'clear')" prompt="primereact $" />
                </Dialog>

                <Dialog visible={displayFinder} breakpoints={{ '960px': '50vw' }} style={{ width: '30vw', height: '18rem' }} onHide={() => setDisplayFinder(false)} maximizable blockScroll={false}>
                    <Tree value={nodes} />
                </Dialog>

                <Galleria ref={galleria} value={images} responsiveOptions={responsiveOptions} numVisible={2} style={{ width: '400px' }}
                    circular fullScreen showThumbnails={false} showItemNavigators item={itemTemplate} />
            </div>
        </div>
        </>
    );
}

export default App;

Step 4

Add the below code in index,html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
      <!-- PrimeReact -->
      <link rel="stylesheet" href="https://unpkg.com/primeicons/primeicons.css" />
      <link rel="stylesheet" href="https://unpkg.com/primereact/resources/themes/lara-light-indigo/theme.css" />
      <link rel="stylesheet" href="https://unpkg.com/primereact/resources/primereact.min.css" />
      <link rel="stylesheet" href="https://unpkg.com/[email protected]/primeflex.min.css" />
      <!-- Dependencies -->
      <script src="https://unpkg.com/react/umd/react.production.min.js"></script>
      <script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
      <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
      <script src="https://unpkg.com/[email protected]/dist/react-transition-group.js"></script>
      <!-- Demo -->
      <script src="./GoogleMaps.js"></script>
      <script src="https://unpkg.com/primereact/core/core.min.js"></script>
      <script src="https://unpkg.com/primereact/gmap/gmap.min.js"></script>
      <script src="https://unpkg.com/primereact/toast/toast.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
      <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>React App</title>
   </head>
   <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

Step 5

Add the below code in App.css 

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.dock-demo .dock-window {
  width: 100%;
  height: 450px;
  position: relative;
  background-image: url('https://www.primefaces.org/primereact/images/dock/window.jpg');
  background-repeat: no-repeat;
  background-size: cover;
}
.dock-demo .p-dock {
  z-index: 1000;
}
.dock-demo .dock-advanced .p-dialog-mask, .dock-demo .dock-advanced .p-galleria-mask, .dock-demo .dock-advanced .p-galleria-mask .p-galleria-item-nav, .dock-demo .dock-advanced .p-toast {
  position: absolute;
}
.dock-demo .dock-advanced .p-dialog .p-dialog-header {
  padding: 0.2rem;
}
.dock-demo .dock-advanced .p-dialog .p-dialog-content {
  padding: 0;
}
.dock-demo .dock-advanced .p-dialog p {
  margin-top: 0;
}
.dock-demo .dock-advanced .p-dialog .p-terminal {
  background-color: #212121;
  color: #fff;
  border: 0 none;
  min-height: 18rem;
  height: 100%;
}
.dock-demo .dock-advanced .p-dialog .p-terminal .p-terminal-command {
  color: #80cbc4;
}
.dock-demo .dock-advanced .p-dialog .p-terminal .p-terminal-prompt {
  color: #ffd54f;
}
.dock-demo .dock-advanced .p-dialog .p-terminal .p-terminal-response {
  color: #9fa8da;
}
.dock-demo .dock-advanced .p-dialog .p-tree {
  height: 100%;
  border-radius: 0;
  border-left-width: 0;
  border-right-width: 0;
  border-bottom-width: 0;
}
.dock-demo .dock-advanced .p-toast {
  top: 20px;
}
.dock-demo .p-menubar {
  padding-top: 0;
  padding-bottom: 0;
  border-radius: 0;
}
.dock-demo .p-menubar .menubar-root {
  font-weight: bold;
  padding: 0 1rem;
}
.dock-demo .p-menubar .p-menuitem-link {
  padding: 0.5rem 0.75rem;
}
.dock-demo .p-menubar .p-menubar-root-list > .p-menuitem > .p-menuitem-link {
  padding: 0.5rem 0.75rem;
}
.dock-demo .p-menubar .p-menubar-root-list > .p-menuitem > .p-menuitem-link > .p-submenu-icon {
  display: none;
}
.dock-demo .p-menubar .p-menubar-end span, .dock-demo .p-menubar .p-menubar-end i {
  padding: 0 0.75rem;
}
.dark-tooltip .p-tooltip .p-tooltip-arrow {
  border-top-color: var(--surface-900);
}
.dark-tooltip .p-tooltip .p-tooltip-text {
  background-color: var(--surface-900);
}

Step 6

Add the below code in the CountryService.js

import data from './contires.json';
export class CountryService {
    getCountries() {
        const result = [];       
         data.map((datas)=>{
            result.push(datas)
        });
        return result;
    }
}
export class NodeService {
    getTreeTableNodes() {
        return fetch('data/treetablenodes.json').then(res => res.json())
                .then(d => d.root);
    }
    getTreeNodes() {
        return fetch('data/treenodes.json').then(res => res.json())
                .then(d => d.root);
    }
}  
export class PhotoService {
    getImages() {
        return fetch('data/photos.json').then(res => res.json())
                .then(d => d.data);
    }
}

Step 7

Add the following code in package.json,

{
  "name": "prime-demo",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "primeicons": "^5.0.0",
    "primereact": "^8.1.1",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-redux": "^8.0.2",
    "react-scripts": "^2.1.3",
    "redux": "^4.2.0",
    "web-vitals": "^2.1.4",
    "primeflex": "^3.1.0",
    "react-transition-group": "^4.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Step 8

Run the following commands

npm i
npm start

PrimeReact UI Component Dock with menu item

PrimeReact UI Component Dock with menu item

Summary

In this article, we learned how to create react project, set PrimeReact UI, and add dock menu UI widgets.