Implement Primereact Chips Component In React JS

Hello Developers in this blog we are going to learn how we can use primereact chips component in our react app

First, you need to create a new app by using the following command

npx create-react-app

Then install the following packages in your app:

npm install primereact primeicons

Then import the CSS file (it is Important otherwise CSS will not be applied)

import "primereact/resources/themes/lara-light-indigo/theme.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";

There are many types of chips components which you can use

1). Basic chip component :-

import './App.css';
import "primereact/resources/themes/lara-light-indigo/theme.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";
import { Chips } from 'primereact/chips';
import { useState } from 'react';

function App() {
  const [values, setValues] = useState([]);

  return (
    <div className="App">
      <div className="card p-fluid">
        <h5>Basic</h5>
        <Chips value={values} onChange={(e) => setValues(e.value)} />
      </div>
    </div>
  );
}

export default App;

Demo:

2). Comma separator:-

<Chips value={values} onChange={(e) => setValues(e.value)} separator="," />

the separator is basically a prop that is used to separate chips from specific value right now there is only one comma separator you can use

Demo:

3). Custom Chip component:

<Chips value={values} onChange={(e) => setValues(e.value)} max={5} itemTemplate={customChip}></Chips>

const customChip = (item) => {
    return (
      <div>
        <span>{item} - (active) </span>
        <i className="pi pi-user-plus" style={{ fontSize: '14px' }}></i>
      </div>
    );
  }

chips component has a prop called itemTemplate which basically accepts a function that returns JSX element

if you want to customize the chip component you can use itemTemplate prop

In the custom chip function, we will get the value of the chips component in the parameter

Demo:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories