Prime React with Javascript

Amir Mustafa
12 min readDec 28, 2022

Introduction:

→ Prime React is a powerful Frontend design library

→ Prime React is a subsidiary of prime faces.

→ Initially Prime Faces gave a frontend (FE) for JAVA technology.

→ Later they have given FE for three Single Page Application (SPA) technologies — React, Angular, Vue JS

i.e. PrimeReact, PrimeNG, PrimeVue

Why do we need PrimeReact?

→ Many of us will ask this question why use it, as we already have Bootstrap, Material UI, etc?

→ PrimeReact is developed keeping React.js in mind. Everything in Prime React is a react component with lots of templates, and UI components features are available.

→ This is one of the hottest technology and is in demand. We can official documentation here.

First Impressions:

Shopping cart, Charts, Calendar
Data Tables

→ We have a great community of React that supports — Mobile, Typescript, etc.

→ Click on components to see all components available.

Eg 1: Calendar component

Eg 2: Formik — Form with validations

Eg 3: Data Tables:

Setting up the Project:

STEP 1: Installing Dependencies:

→ Let us create a React app and implement it.

npx create-react-app <project-name>

Eg. npx create-react-app prime-react

→ Installing Prime React and some dependencies:

npm install primereact primeicons primeflex
cd <project-name>
cd prime-react

STEP 2: Adding Prime Configurations:

→ Open src/index.js

/* 
Prime React Configuration
*/
import "primereact/resources/themes/vela-green/theme.css"; //theme
import "primereact/resources/primereact.min.css"; //core css
import "primeicons/primeicons.css"; //icons
import "primeflex/primeflex.css"; //flex

→ We can change the first import based on the themes available.

→ Starting React App

npm start

src/App.js

import "./App.css";

const App = () => {
return (
<div className="App">
<h2>App Component</h2>
</div>
);
};

export default App;

Adding Google Font:

→ Let us add Google Font’s Ubuntu font to our application.

→ Copy the style tag and CSS property and paste into the application.

src/index.css

@import url('https://fonts.googleapis.com/css2?family=Ubuntu:wght@300&display=swap');
body {
margin: 0;
font-family: 'Ubuntu', sans-serif;
}

→ Let us now implement some Prime React components to test the framework. Let us add a button.

Eg 1: Adding Buttons:

src/App.js

import "./App.css";
import { Button } from "primereact/button";

const App = () => {
return (
<div className="App">
<h2>App Component</h2>
<Button label="Click" icon="pi pi-check" />

<Button label="Primary" />
<Button label="Secondary" className="p-button-secondary" />
<Button label="Success" className="p-button-success" />
<Button label="Info" className="p-button-info" />
<Button label="Warning" className="p-button-warning" />
<Button label="Danger" className="p-button-danger" />
</div>
);
};

export default App;

O/P:

Eg 2: Adding Menubar:

→ Let us add code for Menubar

src/App.js

import "./App.css";
import { Menubar } from "primereact/menubar";
import Counter from "./components/Counter";

const App = () => {
return (
<div className="App">
<Menubar
className="bg-blue-600 p-3 text-3xl text-white"
start={"Prime React"}
/>
<Counter />
</div>
);
};

export default App;

→ Let us now add some logic to this app.

→ Let us add a counter component.

→ Creating a new file:

src/components/Counter.jsx

import React from 'react';

const Counter = () => {
return (
<>
<h2>Counter</h2>
</>
);
}
export default Counter;

src/App.jsx

import "./App.css";
import { Menubar } from "primereact/menubar";
import Counter from "./components/Counter";

const App = () => {
return (
<div className="App">
<Menubar
className="bg-blue-600 p-3 text-3xl text-white"
start={"Prime React"}
/>
<Counter />
</div>
);
};

export default App;

→ Now first we have to make use of Prime’s Grid system. This is available in Grid System.

src/components/Counter.jsx

Using col-3 as class Name = 12/3

import React from 'react';

const Counter = () => {
return (
<>
<div class="grid">
<div className='col-3'>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Possimus assumenda, recusandae non quos accusantium vero odio fugiat quis cumque, quo provident optio beatae debitis tempore dolore necessitatibus pariatur officiis eum?
</div>
</div>
</>
);
}
export default Counter;

TRICK:

Did you know if we need 30 random characters for testing when writing in the div class?

eg1: Type lorem30 + Tab = 30 characters

eg2: lorem100 + Tab = 100 characters will generate for us.

src/components/Counter.jsx

Taking class name as col-6:

import React from 'react';

const Counter = () => {
return (
<>
<div class="grid">
<div className='col-6'>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Possimus assumenda, recusandae non quos accusantium vero odio fugiat quis cumque, quo provident optio beatae debitis tempore dolore necessitatibus pariatur officiis eum?
</div>
</div>
</>
);
}
export default Counter;

→ So for creating a Counter — we will use three components

i.e. Card, Button, and Background Colors

Eg 3: Implementing Counter Logic:

→ Let us now implement the card with two buttons — Increment and Decrement.

→ The idea will be on clicking Increment value will increase and vice-versa for the Decrease button.

src/components/Counter.jsx:

import React from 'react';
import { Card } from 'primereact/card';
import { Button } from 'primereact/button';

const Counter = () => {
return (
<>
<div class="grid">
<div className='col-4'>
// CARD LOGIC
<Card className='m-3 shadow-5 bg-blue-600'>
<h3 className='text-4xl p-0 m-2'>Counter</h3>
<Button label={'Increment'} className='p-button-success mr-2' />
<Button label={'Decrement'} className='p-button-warning' />
</Card>
</div>
</div>
</>
);
}
export default Counter;

Adding Logic for Counter:

Src/components/Counter.jsx

import React, { useState } from 'react';
import { Card } from 'primereact/card';
import { Button } from 'primereact/button';

const Counter = () => {
let [state, setState] = useState({
count: 0
});

// INCREMENT
const incr = () => {
setState({
...state,
count: state.count + 1
});
};

// DECREMENT
const decr = () => {
setState({
...state,
count: state.count - 1 >=0 ? state.count - 1 : 0
});
};

return (
<>
<div class="grid">
<div className='col-4'>
<Card className='m-3 shadow-5 bg-blue-600'>
<h3 className='text-4xl p-0 m-2'>{state.count}</h3>
<Button onClick={incr} label={'Increment'} className='p-button-success mr-2' />
<Button onClick={decr} label={'Decrement'} className='p-button-warning' />
</Card>
</div>
</div>
</>
);
}
export default Counter;

→ Clicking a couple of more times:

→ Clicking Decrement:

Eg 4: Adding Forms:

The idea is to create a Form and when the user clicks the button a Toast message will come.

NOTE:

Toast message is a kind of notification to show messages like message that disappear after some time

→ Let us add a new component.

src/components/Greet.jsx

import React from 'react';
import { Card } from 'primereact/card';
import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button';

const Greet = () => {
return (
<>
<div className='grid mt-2' >
<div className='col-4'>
<Card className='bg-black-alpha-20'>
<form>
<InputText placeholder='Message'/>
<Button label={'Greet'} className="p-button-success ml-2" />
</form>
</Card>
</div>
</div>
</>
);
};
export default Greet;

src/App.jsx

import "./App.css";
import { Menubar } from "primereact/menubar";
import Greet from "./components/Greet";

const App = () => {
return (
<div className="App">
<Menubar
className="bg-blue-600 p-3 text-3xl text-white"
start={"Prime React"}
/>
<Greet />
</div>
);
};

export default App;

→ Let us bind the text now:

src/components/Greet.jsx

import React, { useState } from 'react';
import { Card } from 'primereact/card';
import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button';

const Greet = () => {

const [state, setState] = useState({
msg: ''
});
return (
<>
<div className='grid mt-2' >
<div className='col-4'>
<Card className='bg-black-alpha-20'>
<form>
<pre>{state.msg}</pre>
<InputText
value={state.msg}
onChange={(e) => setState({...state, msg: e.target.value})}
placeholder='Message'/>
<Button label={'Greet'} className="p-button-success ml-2" />
</form>
</Card>
</div>
</div>
</>
);
};
export default Greet;

→ Capturing data from the button and alerting it

src/components/Greet.jsx

import React, { useState } from 'react';
import { Card } from 'primereact/card';
import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button';

const Greet = () => {

const [state, setState] = useState({
msg: ''
});

const greet = () => {
alert(state.msg);
};
return (
<>
<div className='grid mt-2' >
<div className='col-4'>
<Card className='bg-black-alpha-20'>
<form>
<InputText
value={state.msg}
onChange={(e) => setState({...state, msg: e.target.value})}
placeholder='Message'/>
<Button onClick={greet} label={'Greet'} className="p-button-success ml-2" />
</form>
</Card>
</div>
</div>
</>
);
};
export default Greet;

Toast Message:

→ We will be converting alert messages into a toast message on button click.

→ A Toast message appears for some time and then auto hides in three seconds

src/components/Greet.jsx

import React, { useRef, useState } from 'react';
import { Card } from 'primereact/card';
import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button';
import { Toast } from 'primereact/toast';

const Greet = () => {
let toast = useRef(null);

const [state, setState] = useState({
msg: ''
});

const greet = (event) => {
event.preventDefault();
toast.current.show({severity: 'success', summary: 'Success Message', detail: state.msg});
};
return (
<>
<div className='grid mt-2' >
<div className='col-4'>
<Card className='bg-black-alpha-20'>
<form>
<InputText
value={state.msg}
onChange={(e) => setState({...state, msg: e.target.value})}
placeholder='Message'/>
<Button onClick={greet} label={'Greet'} className="p-button-success ml-2" />
</form>
</Card>
<Toast ref={toast} />
</div>
</div>
</>
);
};
export default Greet;

→ After three seconds toast message will disappear.

Data Table:

→ Data table is a tabular representation of Prime React with lots of cool features.

→ Let us implement data tables with one API. This will give 50 sets of user data:

Backend API: https://randomuser.me/api?results=50

→ For this we will use the Axios package for interacting with API

npm install axios –save

→ Let us create a new component. UserList component. We will include Datatables here

src/components/UserList.jsx

import React from 'react';

const UserList = () => {
return (
<>
<h2>User List</h2>
</>
)
};
export default UserList;

→ Connecting UserList in App.js

src/App.js

import "./App.css";
import React from "react";
import { Menubar } from "primereact/menubar";
import UserList from "./components/UserList";

const App = () => {
return (
<div className="App">
<Menubar
className="bg-blue-600 p-3 text-3xl text-white"
start={"Prime React"}
/>
<UserList />
</div>
);
};

export default App;

→ Creating a service page that fetches data from API:

src/service/User.js

import axios from "axios";

export class UserService {
static getAllUsers() {
return axios.get("https://randomuser.me/api?results=50");
}
}

src/App.js

import "./App.css";
import React from "react";
import { Menubar } from "primereact/menubar";
import Counter from "./components/Counter";
import Greet from "./components/Greet";
import UserList from "./components/UserList";

const App = () => {
return (
<div className="App">
<Menubar
className="bg-blue-600 p-3 text-3xl text-white"
start={"Prime React"}
/>
{/* <Counter /> */}
{/* <Greet /> */}
<UserList />
</div>
);
};

export default App;

src/components/UserList.jsx

import React, { useState, useEffect } from 'react';
import { UserService } from '../service/User';

const UserList = () => {

let [state, setState] = useState({
loading: false,
users: [],
errorMessage: null
});

useEffect( () => {
try {
// FETCHING DATA
const fetchData = async () => {
setState({...state, loading: true});
const response = await UserService.getAllUsers();
let { results } = response.data;
console.log(results);
setState({...state, users: results, loading: false});
};
fetchData();
} catch (err) {
console.log(err);
setState({...state, errorMessage: err});
}
}, []);

return (
<>
<h2>User List</h2>
<pre>
{JSON.stringify(state.users)}
</pre>
</>
)
};
export default UserList;

→ We observe data object is printing:

Implementing Data Tables:

import React, { useState, useEffect } from 'react';
import { UserService } from '../service/User';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';

const UserList = () => {

let [state, setState] = useState({
loading: false,
users: [],
errorMessage: null
});

useEffect( () => {
try {
const fetchData = async () => {
setState({...state, loading: true});
const response = await UserService.getAllUsers();
let { results } = response.data;
console.log(results);
setState({...state, users: results, loading: false});
};
fetchData();
} catch (err) {
console.log(err);
setState({...state, errorMessage: err});
}
}, []);

// BELOW METHODS ARE FOR SOME CHANGES IN API DATA
let displaySNo = (rowData) => {
return rowData.login.uuid.substring(1,5);
}
let displayName = (rowData) => {
return <span>{rowData.name.title}. {rowData.name.first} {rowData.name.last}</span>;
}
let displayImage = (rowData) => {
return <img src={rowData.picture.thumbnail} alt="" />;
}
let displayAge = (rowData) => {
return <span>{rowData.dob.age} years</span>;
}

// RENDER
return (
<>
<div className='grid'>
<div className='col'>
<DataTable value={state.users}>
<Column sortable field="login.uuid" header={'S No.'} body={displaySNo} />
<Column sortable field="picture.thumbnail" header={'Image'} body={displayImage} />
<Column sortable field="name" header={'Name'} body={displayName} />
<Column sortable field="dob.age" header={'Age'} body={displayAge} />
<Column sortable field="email" header={'Email'} />
<Column sortable field="location.city" header={'City'} />
<Column sortable field="location.state" header={'State'} />
<Column sortable field="location.country" header={'Country'} />
</DataTable>
</div>
</div>
</>
)
};
export default UserList;

→ The important thing to note is below features:

a. field — API key

b. header — A text that will print in the header column.

c. sortable — making columns sortable

d. body — this column is added for some changes in API data and attached to some functions

let displayName = (rowData) => {
return <span>{rowData.name.title}. {rowData.name.first} {rowData.name.last}</span>;
}

<DataTable value={state.users}>
<Column sortable field="name" header={'Name'} body={displayName} />
</DataTable>

→ Sorted by S No. Let us sort by Age. Click the Age header.

→ We observe Table is sorted by Age.

Closing Thoughts:

Prime React is at present modern way of writing code. It is true that it depends from project to project business requirements for planning software in projects.

In Bootstrap and Material UI, not every feature is component-based. With lots of UI features and React-ready components, Prime React is becoming popular.

Thank you for reading till the end 🙌 . If you enjoyed this article or learned something new, support me by clicking the share button below to reach more people and/or give me a follow on Twitter and subscribe Happy Learnings !! to see some other tips, articles, and things I learn about and share there.

--

--

Amir Mustafa

JavaScript Specialist | Consultant | YouTuber 🎬. | AWS ☁️ | Docker 🐳 | Digital Nomad | Human. Connect with me on https://www.linkedin.com/in/amirmustafa1/