### Installation and Setup Source: https://context7.com/primefaces/primereact/llms.txt Instructions for installing PrimeReact and setting up a theme for styled mode. ```APIDOC ## Installation Install PrimeReact via npm, yarn, or pnpm. ```bash # Using npm npm install primereact # Using yarn yarn add primereact # Using pnpm pnpm add primereact ``` ## Setup with Theme Import a theme CSS file to enable styled mode with pre-built component styles. ```javascript import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; // Import theme (choose one) import 'primereact/resources/themes/lara-light-cyan/theme.css'; // Optional: Import PrimeIcons import 'primeicons/primeicons.css'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(); ``` ``` -------------------------------- ### Start Local Development Server Source: https://github.com/primefaces/primereact/wiki/Building-From-Source Starts the local development server to run the PrimeReact showcase, typically accessible at http://localhost:3000. ```bash npm start ``` -------------------------------- ### Implementing PrimeReact Menu Component Source: https://context7.com/primefaces/primereact/llms.txt This example demonstrates how to define menu items with icons and commands, and how to render them as a basic list, a grouped list, or a popup menu triggered by a button click. ```javascript import React, { useRef } from 'react'; import { Menu } from 'primereact/menu'; import { Button } from 'primereact/button'; import { Toast } from 'primereact/toast'; export default function MenuDemo() { const menu = useRef(null); const toast = useRef(null); const items = [ { label: 'Documents', items: [ { label: 'New', icon: 'pi pi-plus', command: () => { toast.current.show({ severity: 'success', summary: 'New', detail: 'File created' }); } }, { label: 'Search', icon: 'pi pi-search' } ] }, { label: 'Profile', items: [ { label: 'Settings', icon: 'pi pi-cog' }, { label: 'Logout', icon: 'pi pi-sign-out' } ] } ]; const basicItems = [ { label: 'New', icon: 'pi pi-plus' }, { label: 'Search', icon: 'pi pi-search' }, { separator: true }, { label: 'Delete', icon: 'pi pi-trash' } ]; return (
Basic
Grouped
Popup
); } ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/primefaces/primereact/wiki/Building-From-Source Installs all required Node.js packages defined in the package.json file. ```bash npm install ``` -------------------------------- ### Setup PrimeReact with Theme and Icons Source: https://context7.com/primefaces/primereact/llms.txt Demonstrates how to set up PrimeReact in a React application by importing a theme CSS file and optionally PrimeIcons. This enables styled mode with pre-built component styles. ```javascript import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; // Import theme (choose one) import 'primereact/resources/themes/lara-light-cyan/theme.css'; // Optional: Import PrimeIcons import 'primeicons/primeicons.css'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(); ``` -------------------------------- ### Install PrimeReact using npm, yarn, or pnpm Source: https://github.com/primefaces/primereact/blob/master/README.md Demonstrates how to add the PrimeReact library to your project using different package managers. This is the first step to using PrimeReact components in your React application. ```bash # Using npm npm install primereact # Using yarn yarn add primereact # Using pnpm pnpm add primereact ``` -------------------------------- ### PrimeReact InputText Component Examples Source: https://context7.com/primefaces/primereact/llms.txt Demonstrates the usage of the PrimeReact InputText component, showcasing basic input, float labels, invalid states, key filtering for input validation, disabled states, and tooltips. Requires React and primereact. ```javascript import React, { useState } from 'react'; import { InputText } from 'primereact/inputtext'; import { FloatLabel } from 'primereact/floatlabel'; export default function InputTextDemo() { const [value, setValue] = useState(''); const [email, setEmail] = useState(''); const [username, setUsername] = useState(''); return (
{/* Basic Input */} setValue(e.target.value)} placeholder="Enter text" /> {/* With Float Label */} setUsername(e.target.value)} /> {/* Invalid State */} setEmail(e.target.value)} invalid={!email.includes('@')} placeholder="Email" /> {/* With Key Filter (only allow alphanumeric) */} {/* Disabled */} {/* With Tooltip */}
); } ``` -------------------------------- ### React FileUpload Component Examples Source: https://context7.com/primefaces/primereact/llms.txt Demonstrates various modes and configurations for the FileUpload component, including basic, advanced, auto-upload, and custom templates. It utilizes PrimeReact's FileUpload and Toast components for user feedback and file handling. ```javascript import React, { useRef } from 'react'; import { FileUpload } from 'primereact/fileupload'; import { Toast } from 'primereact/toast'; export default function FileUploadDemo() { const toast = useRef(null); const fileUploadRef = useRef(null); const onUpload = () => { toast.current.show({ severity: 'info', summary: 'Success', detail: 'File Uploaded' }); }; const onSelect = (e) => { toast.current.show({ severity: 'info', summary: 'Selected', detail: `${e.files.length} file(s) selected` }); }; const onError = () => { toast.current.show({ severity: 'error', summary: 'Error', detail: 'Upload failed' }); }; const onClear = () => { toast.current.show({ severity: 'warn', summary: 'Cleared', detail: 'Files cleared' }); }; return (
{/* Basic Mode */}
Basic
{/* Advanced Mode */}
Advanced
Drag and drop files here to upload.

} /> {/* Auto Upload */}
Auto Upload
{/* Custom Template */}
Template
{ const { chooseButton, uploadButton, cancelButton } = options; return (
{chooseButton} {uploadButton} {cancelButton}
); }} itemTemplate={(file, props) => (
{file.name} {file.name}
)} />
); } ``` -------------------------------- ### Create Modal Dialogs with PrimeReact Source: https://context7.com/primefaces/primereact/llms.txt This snippet illustrates how to use the PrimeReact Dialog component to create modal overlays. It shows examples of basic dialogs, dialogs with custom footer actions, and maximizable dialogs. ```javascript import React, { useState } from 'react'; import { Dialog } from 'primereact/dialog'; import { Button } from 'primereact/button'; export default function DialogDemo() { const [visible, setVisible] = useState(false); const [visibleFooter, setVisibleFooter] = useState(false); const [maximizable, setMaximizable] = useState(false); const footerContent = (
); return (
); } ``` -------------------------------- ### PrimeReact InputNumber: Basic and Configured Examples Source: https://context7.com/primefaces/primereact/llms.txt Demonstrates the usage of the PrimeReact InputNumber component for various input types including basic integers, numbers without grouping, decimal handling with min/max fraction digits, and setting min/max boundaries. It also shows how to configure currency formatting for different locales (USD and EUR) and add prefixes or suffixes. ```javascript import React, { useState } from 'react'; import { InputNumber } from 'primereact/inputnumber'; export default function InputNumberDemo() { const [value1, setValue1] = useState(42723); const [value2, setValue2] = useState(58151); const [price, setPrice] = useState(1500); const [percent, setPercent] = useState(50); return (
{/* Basic Integer */}
setValue1(e.value)} />
{/* Without Grouping */}
setValue2(e.value)} useGrouping={false} />
{/* Decimal */}
console.log(e.value)} minFractionDigits={2} maxFractionDigits={5} />
{/* Min/Max Boundaries */}
setPercent(e.value)} min={0} max={100} />
{/* Currency */}
setPrice(e.value)} mode="currency" currency="USD" locale="en-US" />
{/* Currency - Different Locale */}
setPrice(e.value)} mode="currency" currency="EUR" locale="de-DE" />
{/* Prefix and Suffix */}
setPercent(e.value)} suffix="%" />
{/* With Buttons */}
setValue1(e.value)} showButtons buttonLayout="horizontal" />
{/* Vertical Buttons */}
setValue1(e.value)} showButtons buttonLayout="vertical" style={{ width: '4rem' }} />
); } ``` -------------------------------- ### Implementing PrimeReact Charts Source: https://context7.com/primefaces/primereact/llms.txt This example demonstrates how to initialize and render multiple chart types (bar, line, pie, and doughnut) within a React component. It uses the useEffect hook to populate chart data and defines common options for chart customization. ```javascript import React, { useState, useEffect } from 'react'; import { Chart } from 'primereact/chart'; export default function ChartDemo() { const [barData, setBarData] = useState({}); const [lineData, setLineData] = useState({}); const [pieData, setPieData] = useState({}); useEffect(() => { setBarData({ labels: ['January', 'February', 'March', 'April', 'May', 'June'], datasets: [ { label: 'Sales', backgroundColor: '#42A5F5', data: [65, 59, 80, 81, 56, 55] }, { label: 'Revenue', backgroundColor: '#66BB6A', data: [28, 48, 40, 19, 86, 27] } ] }); setLineData({ labels: ['January', 'February', 'March', 'April', 'May', 'June'], datasets: [ { label: 'First Dataset', data: [65, 59, 80, 81, 56, 55], fill: false, borderColor: '#42A5F5', tension: 0.4 }, { label: 'Second Dataset', data: [28, 48, 40, 19, 86, 27], fill: false, borderColor: '#FFA726', tension: 0.4 } ] }); setPieData({ labels: ['A', 'B', 'C'], datasets: [ { data: [540, 325, 702], backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56'], hoverBackgroundColor: ['#FF6384', '#36A2EB', '#FFCE56'] } ] }); }, []); const chartOptions = { plugins: { legend: { labels: { usePointStyle: true } } } }; return (
Bar Chart
Line Chart
Pie Chart
Doughnut Chart
); } ``` -------------------------------- ### PrimeReact Button Component Examples Source: https://context7.com/primefaces/primereact/llms.txt Illustrates various ways to use the PrimeReact Button component, including basic usage, icons, loading states, severity variants, sizes, badges, and disabled states. It requires React and the primereact library. ```javascript import React, { useState } from 'react'; import { Button } from 'primereact/button'; export default function ButtonDemo() { const [loading, setLoading] = useState(false); const handleClick = () => { setLoading(true); setTimeout(() => setLoading(false), 2000); }; return (
{/* Basic Button */}
); } ``` -------------------------------- ### React Functional Component Structure Source: https://github.com/primefaces/primereact/blob/master/CODING_STANDARDS.md Provides an example of the preferred functional component pattern in React for better readability and performance. ```javascript const MyComponent = () => { return (
{/* JSX */}
); }; ``` -------------------------------- ### PrimeReact Dropdown Component Examples (React) Source: https://context7.com/primefaces/primereact/llms.txt Demonstrates various implementations of the PrimeReact Dropdown component in React. This includes basic dropdowns, dropdowns with filtering, clear buttons, grouped options, custom item templates, and editable dropdowns. It utilizes React hooks for state management. ```javascript import React, { useState } from 'react'; import { Dropdown } from 'primereact/dropdown'; export default function DropdownDemo() { const [selectedCity, setSelectedCity] = useState(null); const [selectedCountry, setSelectedCountry] = useState(null); const cities = [ { name: 'New York', code: 'NY' }, { name: 'Rome', code: 'RM' }, { name: 'London', code: 'LDN' }, { name: 'Istanbul', code: 'IST' }, { name: 'Paris', code: 'PRS' } ]; const groupedCities = [ { label: 'Germany', code: 'DE', items: [ { label: 'Berlin', value: 'Berlin' }, { label: 'Frankfurt', value: 'Frankfurt' } ] }, { label: 'USA', code: 'US', items: [ { label: 'Chicago', value: 'Chicago' }, { label: 'Los Angeles', value: 'Los Angeles' } ] } ]; const cityTemplate = (option) => { return (
{option.code} {option.name}
); }; return (
{/* Basic Dropdown */} setSelectedCity(e.value)} options={cities} optionLabel="name" placeholder="Select a City" className="w-full md:w-14rem" /> {/* With Filter */} setSelectedCity(e.value)} options={cities} optionLabel="name" filter filterPlaceholder="Search..." placeholder="Select a City" /> {/* With Clear Button */} setSelectedCity(e.value)} options={cities} optionLabel="name" showClear placeholder="Select a City" /> {/* Grouped Options */} setSelectedCountry(e.value)} options={groupedCities} optionLabel="label" optionGroupLabel="label" optionGroupChildren="items" placeholder="Select a City" /> {/* Custom Item Template */} setSelectedCity(e.value)} options={cities} optionLabel="name" itemTemplate={cityTemplate} placeholder="Select a City" /> {/* Editable */} setSelectedCity(e.value)} options={cities} optionLabel="name" editable placeholder="Select or type" />
); } ``` -------------------------------- ### Implementing DataTable with Advanced Features in React Source: https://context7.com/primefaces/primereact/llms.txt This example demonstrates how to configure a PrimeReact DataTable with sorting, filtering, pagination, and row selection. It utilizes React hooks for state management and custom body templates for rendering formatted price and status columns. ```javascript import React, { useState, useEffect } from 'react'; import { DataTable } from 'primereact/datatable'; import { Column } from 'primereact/column'; import { InputText } from 'primereact/inputtext'; export default function DataTableDemo() { const [products, setProducts] = useState([]); const [selectedProducts, setSelectedProducts] = useState(null); const [globalFilter, setGlobalFilter] = useState(''); const [loading, setLoading] = useState(true); useEffect(() => { const data = [ { id: '1000', code: 'f230fh0g3', name: 'Bamboo Watch', category: 'Accessories', quantity: 24, price: 65, inventoryStatus: 'INSTOCK' }, { id: '1001', code: 'nvklal433', name: 'Black Watch', category: 'Accessories', quantity: 61, price: 72, inventoryStatus: 'INSTOCK' }, { id: '1002', code: 'zz21cz3c1', name: 'Blue Band', category: 'Fitness', quantity: 2, price: 79, inventoryStatus: 'LOWSTOCK' }, { id: '1003', code: '244wgerg2', name: 'Blue T-Shirt', category: 'Clothing', quantity: 25, price: 29, inventoryStatus: 'INSTOCK' }, { id: '1004', code: 'h456wer53', name: 'Bracelet', category: 'Accessories', quantity: 0, price: 15, inventoryStatus: 'OUTOFSTOCK' } ]; setProducts(data); setLoading(false); }, []); const priceBodyTemplate = (rowData) => { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(rowData.price); }; return ( setSelectedProducts(e.value)} dataKey="id" > ); } ``` -------------------------------- ### Implementing PrimeReact Calendar Component Source: https://context7.com/primefaces/primereact/llms.txt This example demonstrates various configurations of the PrimeReact Calendar component, including basic date selection, range selection, multiple date selection, time picking, and specialized views like month/year pickers. It utilizes React state hooks to manage selected values and showcases properties like showIcon, selectionMode, and view. ```javascript import React, { useState } from 'react'; import { Calendar } from 'primereact/calendar'; export default function CalendarDemo() { const [date, setDate] = useState(null); const [dates, setDates] = useState(null); const [dateRange, setDateRange] = useState(null); const [datetime, setDatetime] = useState(null); const [time, setTime] = useState(null); return (
setDate(e.value)} /> setDate(e.value)} dateFormat="dd/mm/yy" /> setDate(e.value)} showIcon /> setDateRange(e.value)} selectionMode="range" readOnlyInput /> setDates(e.value)} selectionMode="multiple" readOnlyInput /> setDatetime(e.value)} showTime hourFormat="24" /> setTime(e.value)} timeOnly /> setDate(e.value)} view="month" dateFormat="mm/yy" /> setDate(e.value)} view="year" dateFormat="yy" /> setDate(e.value)} inline /> setDate(e.value)} minDate={new Date()} maxDate={new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)} /> setDate(e.value)} disabledDays={[0, 6]} />
); } ``` -------------------------------- ### Compile SASS Theme Files Source: https://github.com/primefaces/primereact/wiki/Migration-Guide-for-Templates This command compiles SASS files to generate CSS, typically used after updating theme files. Ensure you have SASS installed globally. The command updates files in the 'public/theme' directory. ```bash sass --update public/theme:public/theme ``` -------------------------------- ### PrimeReact Checkbox Component Implementation (JavaScript) Source: https://context7.com/primefaces/primereact/llms.txt Demonstrates how to use the PrimeReact Checkbox component for single binary selection and dynamic grouping of options. It includes examples for handling checked states, managing selections in an array, and rendering disabled checkboxes. Dependencies include React and the PrimeReact Checkbox module. ```javascript import React, { useState } from 'react'; import { Checkbox } from 'primereact/checkbox'; export default function CheckboxDemo() { const [checked, setChecked] = useState(false); const [ingredients, setIngredients] = useState([]); const pizzaIngredients = [ { name: 'Cheese', key: 'C' }, { name: 'Mushroom', key: 'M' }, { name: 'Pepper', key: 'P' }, { name: 'Onion', key: 'O' } ]; const onIngredientsChange = (e) => { let _ingredients = [...ingredients]; if (e.checked) _ingredients.push(e.value); else _ingredients = _ingredients.filter(ingredient => ingredient.key !== e.value.key); setIngredients(_ingredients); }; return (
{/* Basic Checkbox */}
setChecked(e.checked)} checked={checked} />
{/* Dynamic Checkboxes */}
{pizzaIngredients.map((ingredient) => (
item.key === ingredient.key)} />
))}
{/* Disabled */}
); } ``` -------------------------------- ### Import PrimeReact Theme CSS Source: https://github.com/primefaces/primereact/blob/master/README.md Illustrates how to import a theme's CSS file for PrimeReact's styled mode. This is necessary to apply the visual styling of a chosen theme, like 'lara-light-cyan', to your components. ```javascript // theme import 'primereact/resources/themes/lara-light-cyan/theme.css'; ``` -------------------------------- ### Menu Component Configuration Source: https://context7.com/primefaces/primereact/llms.txt Details on how to configure the Menu component using the model property for items and sub-items. ```APIDOC ## Menu Component Configuration ### Description The Menu component allows for the creation of navigation lists. It supports nested groups, icons, and command callbacks for individual items. ### Properties - **model** (array) - Required - An array of menu items. Each item can contain 'label', 'icon', 'command', 'items' (for sub-menus), or 'separator'. - **popup** (boolean) - Optional - Defines if the menu should be displayed as a popup. Default is false. ### Usage Example ```javascript const items = [ { label: 'New', icon: 'pi pi-plus', command: () => { /* logic */ } }, { label: 'Search', icon: 'pi pi-search' } ]; ``` ### Popup Usage To use as a popup, set the 'popup' property to true and use the 'toggle' method on the component reference. ```javascript