DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Top React Libraries for Data-Driven Dashboard App Development
  • Mastering React App Configuration With Webpack
  • Optimizing User Experience in React Native
  • Revolutionizing Network Operations With Automated Solutions: A Deep Dive Into ReactJS

Trending

  • Contextual AI Integration for Agile Product Teams
  • Navigating the LLM Landscape: A Comparative Analysis of Leading Large Language Models
  • Agentic AI and Generative AI: Revolutionizing Decision Making and Automation
  • Building AI-Driven Intelligent Applications: A Hands-On Development Guide for Integrating GenAI Into Your Applications
  1. DZone
  2. Coding
  3. JavaScript
  4. Prime React UI Component Dock With Menu Item

Prime React UI Component Dock With Menu Item

In this article, we will learn how to create a React project, set up PrimeReact UI, and add dock menu UI widgets. We are using JSX with React.js.

By 
abhishek saini user avatar
abhishek saini
·
Oct. 04, 23 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
3.2K Views

Join the DZone community and get the full member experience.

Join For Free

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 a React application.
  • Installation of Prime face.
  • How to Apply Dock of Prime face in React Js.

Step 1

Run the below command for creating a React Js application.

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


Step 2

Run the below command for installing PrimeReact.

JSX
 
npm install primereact primeicons


Step 3

Add the below code in the App.js.

JSX
 
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" data-fr-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" data-fr-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" data-fr-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.

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/primeflex@3.1.2/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/react-transition-group@4.4.2/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>
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.

JSX
 
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.

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.

JSX
 
npm i
npm start


Summary

In this article, we learned how to create a React project, set Prime React UI, and add dock menu UI widgets.

JavaScript UI app Command (computing) PRIME (PLC) React (JavaScript library)

Published at DZone with permission of abhishek saini. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Top React Libraries for Data-Driven Dashboard App Development
  • Mastering React App Configuration With Webpack
  • Optimizing User Experience in React Native
  • Revolutionizing Network Operations With Automated Solutions: A Deep Dive Into ReactJS

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!