how to react-js-pagination implement with react hook data table - reactjs

How to integrate pagination code with hooks method data table with. im using react-js-pagination nmp package but there is no one explanation for implement with hook method program.
This my data table code:
import React, { useEffect, useState } from 'react';
import axios from 'axios'
import 'bootstrap/dist/css/bootstrap.min.css';
import {Link} from 'react-router-dom';
const ProTable = () => {
const [data, setData] = useState([]);
useEffect(() => {
loadData();
}, []);
const loadData = async() => {
axios.get('http://localhost:5000/api/clientgetdata')
.then(response => {
setData(response.data.map);
}
const delPro = (item,e) => {
var option = window.confirm(`Are you sure to delete ${e.clientName} OF ${item.projectName}`)
if(option){
const check = axios.delete(`http://localhost:5000/api/clientdelpro/${e.clientName}/${item.projectName}`).then(res => {
//console.log(clientname)
window.location.reload(false)
})
}
}
return (
<>
<div className="row addButton">
<div className="col-lg-1">
<Link
className="btn btn-outline-primary mr-2"
to={'/client/addpro'}
>New</Link>
</div>
<div className="col-lg-1">
{/* <button variant="primary" >Delete</button> */}
</div>
</div>
<div className="row hrtable">
<div className="col-lg-10 col-sm-6 col-md-6">
<div className="table-responsive tcenter" >
<table className="table table-bordered table-hover table-sm">
<thead className="thead-dark">
<tr>
<th scope="col"><input type="checkbox" /></th>
<th scope="col">Client Name</th>
<th scope="col">Project Name</th>
<th scope="col">Status</th>
<th>Action</th>
</tr>
</thead>
{ (data.length > 0) ? data.map( e => {
return (
<>
{e.project.map(item=> {
return (
<tbody>
<tr>
<th scope="row">
<input type="checkbox"/>
</th>
<td><ul>{e.clientName}</ul></td>
<td><ul>{item.projectName}</ul></td>
<td><ul>{item.proStatus}</ul></td>
<td>
<Link
className="btn btn-outline-primary mr-2"
to={`/project/edit/${e.clientName}/${item.projectName}`} >
Edit
</Link>
<button
className="btn btn-danger"
onClick={() => delPro(item,e)}>
Delete
</button>
</td>
</tr>
</tbody>
);
})}
</>
);
}) : <tr><td colSpan="5">No Records Found</td></tr> }
</table>
</div>
</div>
</div>
</>
);
}
export default ProTable;
This is Reaci-js-pagination code.
I am trying to follow this tutorial to create a pagination in my application https://www.npmjs.com/package/react-js-pagination#usage
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Pagination from "react-js-pagination";
require("bootstrap/less/bootstrap.less");
class App extends Component {
constructor(props) {
super(props);
this.state = {
activePage: 15
};
}
handlePageChange(pageNumber) {
console.log(`active page is ${pageNumber}`);
this.setState({activePage: pageNumber});
}
render() {
return (
<div>
<Pagination
activePage={this.state.activePage}
itemsCountPerPage={10}
totalItemsCount={450}
pageRangeDisplayed={5}
onChange={this.handlePageChange.bind(this)}
/>
</div>
);
}
}
plz help me how integrate both code

Try by converting it into hooks
const [state, setState] = React.useState({activePage: 15});
const handlePageChange=(pageNumber) => {
setState({activePage: pageNumber});
// make api call for next page
}
return (
<div>
<Pagination
activePage={state.activePage}
itemsCountPerPage={10} // pass your fixed item per pages
totalItemsCount={450} // total item -> per-page * no of page
pageRangeDisplayed={5}
onChange={handlePageChange}
/>
</div>
);

Related

react js state value always false

hello im trying to make a array that contain a objects and i want to map this array into two tables :thisis stricture of array:
0
:
{title: 'uml', agreement: false}
1
:
{title: 'react', agreement: false}
2
:
{title: 'laravel', agreement: false}
length
:
3
[[Prototype]]
:
Array(0)
and i have a checkbox that make agreement true or false .
but the problem is everytime the agreement is false.
i want to send objects to first table if is true and to seconde table if is false but everytime is send to first table with false agreement .
this is all of code:
some functions is just to show the values of states
import './App.css';
import { useRef, useState } from 'react';
function App() {
const [modules,setModules]=useState([])
const [agreement,setAgreement]=useState()
const [title,setTitle]=useState()
const checkbox=useRef()
function handlecheck(){
setAgreement(checkbox.current.checked)
}
function handlechange(event){
setTitle(event.target.value)
}
function ajouter(){
setModules([...modules,{title,agreement}])
}
function affich(){
return console.log(modules)
}
return (
<div className="App">
<section class="container cd-table-container">
<h2 class="cd-title">Insert Table Record:</h2>
<input onChange={(event)=>handlechange(event)} type="text" class="cd-search table-filter" data-table="order-table" placeholder="module name" />
<button className='ajouter' onClick={()=>ajouter()} >Ajouter</button>
<button className='ajouter' onClick={()=>affich()} >affich</button>
<input type={"checkbox"} ref={checkbox} onChange={(event)=>handlecheck(event)} />
<table class="cd-table table">
<thead>
<tr>
<th>modules regionaux</th>
</tr>
</thead>
<tbody>
{
modules.map((elm,index)=>{
if(elm.agreement=true){
return (<tr>
<td>{elm.title}</td>
</tr>)
}
})
}
</tbody>
</table>
<br></br>
<table class="cd-table table">
<thead>
<tr>
<th>modules non regionaux</th>
</tr>
</thead>
<tbody>
{
modules.map((elm,index)=>{
if(elm.agreement=false){
return (<tr>
<td>{elm.title}</td>
</tr>)
}
})
}
</tbody>
</table>
</section>
</div>
);
}
export default App;
so first you don't have to use (useRef) hock just use (useState) will be better , second you were using the if statement with the assign operator sign you should use the double equal sign or the triple sign this the full code
import './App.css';
import { useRef, useState } from 'react';
function App() {
const [modules, setModules] = useState([])
const [agreement, setAgreement] = useState()
const [title, setTitle] = useState()
function handlecheck(e) {
setAgreement(e)
}
function handlechange(event) {
setTitle(event.target.value)
}
function ajouter() {
setModules([...modules, { title, agreement }])
}
function affich() {
return console.log(modules)
}
return (
<div className="App">
<section class="container cd-table-container">
<h2 class="cd-title">Insert Table Record:</h2>
<input onChange={(event) => handlechange(event)} type="text" class="cd-search table-filter" data-table="order-table" placeholder="module name" />
<button className='ajouter' onClick={() => ajouter()} >Ajouter</button>
<button className='ajouter' onClick={() => affich()} >affich</button>
<input type={"checkbox"} onChange={(event) => handlecheck(event.target.checked)} />
<table class="cd-table table">
<thead>
<tr>
<th>modules regionaux</th>
</tr>
</thead>
<tbody>
{
modules.map((elm, index) => {
if (elm.agreement === true) {
return (<tr>
<td>{elm.title}</td>
</tr>)
}
})
}
</tbody>
</table>
<br></br>
<table class="cd-table table">
<thead>
<tr>
<th>modules non regionaux</th>
</tr>
</thead>
<tbody>
{
modules.map((elm, index) => {
if (elm.agreement === false) {
return (<tr>
<td>{elm.title}</td>
</tr>)
}
})
}
</tbody>
</table>
</section>
</div>
);
}
export default App;

How to pass partial data to a parent component in react

I have the following Component TBorrowed
import React, { Fragment, useState} from "react";
import {Link} from 'react-router-dom';
const EditItem = ({ item }) => {
const [name, setName] = useState(item.name)
const saveData = async (e) => {
e.preventDefault();
const body = { name}
await fetch(`http://127.0.0.1:5000/item/edit/${item.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
})
}
return (
<Fragment>
<Link className="link" data-toggle="modal" data-target={`#id${item.id}`} >{item.name}</Link>
<div className="modal" id={`id${item.id}`}>
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h4 className="modal-title">Edit Item</h4>
</div>
<div className="modal-body">
<label>Name</label>
<input value={name} onChange={e => { setName(e.target.value) }} type="text" />
</div>
<div className="modal-footer">
<button onClick={e => { saveData(e) }} type="button" className="btn btn-outline-success ml-auto" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
</Fragment>
)
}
export default EditItem;
The above is called in another component, Main as shown below
import React, { useState} from 'react';
import TBorrowed from './TBorrowed';
const Main = () => {
const [items, setItems] = useState([]);
...MANY ITEMS SKIPPED...
return (
<table className="layout">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Code</th>
</tr>
</thead>
<tbody>
{
items.map((item, index) => (
<tr key={item.id}>
<td>{index + 1}</td>
<td>{item.name}</td>
<td>{<TBorrowed item={item} />}</td>
</tr>
))
}
</tbody>
</table>
)
}
export default Main;
The above works well where I am able to see the item code in the Main component's <td></td> when rendered, which when I click, I am able to edit the particular item in a modal.
My issue is I no longer want to edit an item in a modal but I want it rendered on it's own page for editing.
When I try it without a data-toggle = "modal" in the TBorrowed component, I get all the contents of the TBorrowed component displaying in the Main component where the modal is called i.e <td>{<TBorrowed item={item} />}</td>. All the data in TBorrowed is shown in that <td></td> instead of just the item.code as it was showing while using the modal
My code has some parts missing so it can fit here.
Please assist, and if there's more information required I'll provide it.

Argument appears to not be a ReactComponent. Keys:

I need to print a component for that i'm using react-to-print package.
here everything is working fine. when i try to customize it based on my requirement
i'm getting this error. i tried to search in the google but didn't get any proper solution.
so here i posted.
this is the component i want to print it.
const ModalContent=React.forwardRef(({ ticketDetails, bookingHistory, movie }, ref)=>{
var op = movie.filter((e, i, arr) => {
return e._id == bookingHistory.movieId
})
const [invoiceSummary, setinvoiceSummary] = useState({
totalSeatCount: bookingHistory.seatSeletion.length,
ticketPrice: op[0].ticketPrice,
gstRate: op[0].gst,
serviceCharge: op[0].serviceCharge
})
const [summaryFinalOk, setsummaryFinalOk] = useState(true);
useImperativeHandle(ref, () => ({
showTick() {
setsummaryFinalOk(true);
}
}));
return (<>
<div className="card">
{summaryFinalOk ?<>
<svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
<circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
<path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
</svg>
<h3>your Ticket has been Confirmed</h3></>
: <>
<div className="card-header bg-black"></div>
<div className="card-body">
<div className="row">
<div className="row text-center">
<h3 className="text-uppercase text-center mt-3 invoice-h3" >Invoice</h3>
</div>
<div className="row mx-3">
<table className="table">
<thead>
<tr>
<th scope="col">Ticket Order Summary </th>
<th scope="col">Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ticket price</td>
<td>{invoiceSummary.totalSeatCount} x {invoiceSummary.ticketPrice} = {invoiceSummary.totalSeatCount * invoiceSummary.ticketPrice}<i class="fa-solid fa-indian-rupee-sign"></i></td>
</tr>
<tr>
<td>Gst</td>
<td>{invoiceSummary.gstRate} % ={(invoiceSummary.totalSeatCount * invoiceSummary.ticketPrice) * invoiceSummary.gstRate / 100}<i class="fa-solid fa-indian-rupee-sign"></i></td>
</tr>
<tr>
<td>Internet Handling</td>
<td>{invoiceSummary.totalSeatCount} x{invoiceSummary.serviceCharge}={invoiceSummary.totalSeatCount * invoiceSummary.serviceCharge}<i class="fa-solid fa-indian-rupee-sign"></i></td>
</tr>
</tbody>
</table>
</div>
<hr></hr>
</div>
</div>
</>}
</div>
</>);
})
in index.js
import React, { memo, useEffect, useState, useRef, useCallback } from 'react';
import {useReactToPrint} from 'react-to-print';
import ModalContent from './modalContent';
function TicketBooking({ }) {
const tick=useRef();
//print the data
const handlePrint = useReactToPrint({
content: () => tick.current
});
const showcontent = ()=>{
}
return (
<div className="container screen-design">
<button onclick={showcontent}>showcontent</button>
<ModalContent ticketDetails={""} ref={tick} bookingHistory={[]} movie={""}></ModalContent>
<button onclick={handlePrint}>print</button>
</div>)
}
export default memo(TicketBooking);
so when i click the showcontent the button i can able to see the content. but when i click the print button i got following error.
can any one know how to solve this.

How can i change this code to react redux

Here i want to change this code to react redux. How i can change this code using react redux. Kindly provide any solutions for changing this code to react redux using GET method api. As iam new to react js how can i change this code using react redux.
import React from "react";
import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
export default function User() {
const [users, setUsers] = useState([]);
const f = async () => {
const res = await fetch("https://reqres.in/api/userspage=1");
const json = await res.json();
setUsers(json.data);
};
useEffect(() => {
f();
}, []);
const handleLogout = (e) => {
localStorage.clear();
window.location.pathname = "/";
}
return (
<div>
<h1>List Users</h1>
<div>
<button onClick={handleLogout}>Logout</button>
<nav>
<Link to="/Home">Home</Link>
</nav>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>First_name</th>
<th>Last_name</th>
<th>Email</th>
<th>Avatar</th>
</tr>
</thead>
<tbody>
{users.length &&
users.map((user) => {
return (
<tr>
<td> {user.id}</td>
<td>{user.first_name}</td>
<td> {user.last_name} </td>
<td>{user.email}</td>
<td> <img key={user.avatar} src={user.avatar} alt="avatar" /></td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}

How do I get my react app to display object information in my bootstrap modal when they click on a list item?

I've been trying for a while now, with no luck on trying to get it to where a user clicks on a table item that it brings up a window with the information on what they clicked. I have a JSON file and would like it to read the information from the file instead of the actual file page.
Here is the main app page
import './App.scss';
import list from './list.json';
import Table from 'react-bootstrap/Table';
import MyVerticallyCenteredModal from './components/modal';
function App() {
const [modalShow, setModalShow] = useState(false);
const [menu, setMenu] = useState(
{
food: ""
}
);
const handleChange = (event) => {
setMenu({
food: event.target.value
});
}
const [looped] = useState(
list.map((obj, i) => {
return (
<tr key={i} onClick={() => {
setModalShow(true);
handleChange(obj.food)
console.log(obj.food)
}
}>
<td>{i + 1}</td>
<td>{obj.food}</td>
<td>{obj.description}</td>
<td>${obj.price.toString()}</td>
</tr>
)
})
);
// console.log(menu);
return (
<div className="menu-template container-lg">
<div className="mt-5 mb-5 d-flex">
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>Meal Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{
looped
}
</tbody>
</Table>
</div>
<MyVerticallyCenteredModal
food={food}
description={description}
price={price}
show={modalShow}
onHide={() => setModalShow(false)}
/>
</div>
);
}
export default App;
Here is the modal
import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';
import image from '../assets/image1.jpg';
function MyVerticallyCenteredModal(props) {
return (
<Modal
{...props}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header>
<Modal.Title id="contained-modal-title-vcenter">
<img src={image} alt="..." width="100%" />
</Modal.Title>
</Modal.Header>
<Modal.Body>
<h4>
Some Tasty Food!</h4>
<p>
This is the best food you've ever eaten!
</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={props.onHide} variant="danger">Close</Button>
</Modal.Footer>
</Modal>
);
}
export default MyVerticallyCenteredModal;```
From the first look at this, it doesn't look like you are adding an event to the handleChange() function, just passing a parameter from the obj dictionary. Also, since you are only showing a modal when there is a value in the menu, I would just use that as the indicator to show.
Here's a small sample:
const [menu, setMenu] = useState(null);
const [looped] = useState(
list.map((obj, i) => {
return (
<tr key={i} onClick={() => setMenu({food: obj.food, description: obj.description, price: obj.price, <etc...>})}>
<td>{i + 1}</td>
<td>{obj.food}</td>
<td>{obj.description}</td>
<td>${obj.price.toString()}</td>
</tr>
)
})
);
// console.log(menu);
return (
<div className="menu-template container-lg">
<div className="mt-5 mb-5 d-flex">
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>Meal Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{
looped
}
</tbody>
</Table>
</div>
<MyVerticallyCenteredModal
{...menu} /** Just spreading out the dictionary from the state */
show={!!menu} // Double ! makes it a true or false
onHide={() => setMenu(null)} // or false..
/>
</div>
);
} ```
----------
Because you have now passed the props from that state, you can now use
them on the modal like this:
function MyVerticallyCenteredModal(props) {
const {food, descriptions, price} = props
console.log('view passed props')
....
}
In the model file.
When you're exporting the component remove default.
Use something like this-
export {MyVetrical....}
Lemme know if it works

Resources