I want to make my table row dynamic so it can automatically add new data from the MySQL database but I don't know how. Can you help me?
Here is my static data that I wanted to make dynamic.
const data = {
rows: [
{
Campus_name: 'National Arabella SHS',
tel_number: ' 123-12-123',
action:
<div className='action-icon-container'>
<Tooltip title="Edit" trigger="hover">
<Link to='/admin/campus/edit-campus/:id' state={{bc_edit_type : 1}}><MdEdit className='action-icon edit' /></Link>
</Tooltip>
</div>
},
{
Campus_name: 'College of Arabella - Main',
tel_number: ' 123-12-123',
action:
<div className='action-icon-container'>
<Tooltip title="Edit" trigger="hover">
<MdEdit className='action-icon edit' />
</Tooltip>
</div>
},
{
Campus_name: 'College of Arabella Extension',
tel_number: ' 123-12-123',
action:
<div className='action-icon-container'>
<Tooltip title="Edit" trigger="hover">
<MdEdit className='action-icon edit' />
</Tooltip>
</div>
},
]
};
Here is the part where I get the data from the database and store it in 'campusValues' variable.
const CampusPage = () => {
const [campusValues, setCampusValues] = useState([]);
const GetCampusValues = () => {
Axios.get("http://localhost:5000/campusValues").then((response) => {
console.log(response);
setCampusValues(response.data);
});
}
useEffect(() => {
let ignore = false;
if (!ignore)
GetCampusValues();
return () => { ignore = true; }
},[]);
return (...);
}
export default CampusPage
To make a dynamic table just map the table rows:
<table>
<tr>
<th>...</th>
<th>...</th>
<th>...</th>
</tr>
{
campusValues.map(value => (
<tr key={...}>
<td>{value.id}</td>
<td>{value.name}</td>
<td>...</td>
</tr>
))
}
</table>
Related
Description
i'm working on reactjs and apollo client project. i'm also developing deleteUser feature. delete mutation is working but without modal confirmation. i want to add modal confirm when admin click delete button. it means, delete mutation is executed after admin click on button yes inside modals.
Problem
When i'm clicking delete user button, mutation delete is executed first than modal is show. and when i'm click "yes" button, it'll be refetching data.
Here's the code :
import React, { useState, useEffect } from "react";
import { Table, Button } from "react-bootstrap";
import { useMutation } from "#apollo/client";
import { GET_ALL_USERS } from "../../../gql/query";
import { DELETE_USER } from "../../../gql/mutation";
import ModalEdit from "../Modals/ModalEdit";
import ModalConfirm from "../../Common/Modals/ModalConfirm";
const TableUserInfo = ({ data, variables }) => {
const [showModal, setShowModal] = useState(false);
const [username, setUsername] = useState("");
const [isDeleting, setIsDeleting] = useState(false);
const handleShowModal = () => setShowModal(true);
const handleCloseModal = () => setShowModal(false);
const [deleteUser, { error, loading, refetch }] = useMutation(DELETE_USER);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error</p>;
if (
!data ||
!data.getAllUsers ||
!data.getAllUsers.rows ||
!data.getAllUsers.rows.length
) {
return <p className="text-center"> Tidak ada data tersedia </p>;
}
// delete user handler
const handleDelete = (userToDelete) => {
setIsDeleting( true );
deleteUser({
variables: { username: userToDelete },
update(cache, { data }) {
const { getAllUsers } = cache.readQuery({
query: GET_ALL_USERS,
variables,
});
cache.writeQuery({
query: GET_ALL_USERS,
variables,
data: {
getAllUsers: {
...getAllUsers,
totalItems: getAllUsers.totalItems - 1,
rows: getAllUsers.rows.filter((user) => user.username !== userToDelete)
}
}
});
},
onError: (error) => {
console.log(JSON.stringify(error, null, 2));
},
});
}
return (
<Table responsive>
<thead>
<tr>
<th>No</th>
<th>Nama Pengguna</th>
<th>Role Akun</th>
<th>Email</th>
<th>Tanggal Daftar</th>
<th>Status Akun</th>
<th>Pengaturan</th>
</tr>
</thead>
<tbody>
{data.getAllUsers.rows.map((user, index) => (
<tr key={user.username}>
<td>{index + 1}</td>
<td>{user.full_name}</td>
<td>{user.group_id}</td>
<td>{user.email}</td>
<td>{user.created_dtm}</td>
<td>{user.status}</td>
<td>
{user.status !== "ACTIVE"
? [
<Button
key="Aktifkan Akun"
className="d-block mb-2 text-white bg-secondary w-100"
>
Aktifkan Akun
</Button>,
<Button
key="Ganti Role Akun"
className="d-block mb-2 btn-block btn-sm w-100"
disabled
>
Ganti Role Akun
</Button>,
]
: user.group_id === "admin"
? [
<Button
key="Ganti Role Akun"
variant="outline-success"
className="d-block btn-sm mb-2 w-100"
>
Ganti Role Akun
</Button>,
]
: [
<Button
key="Pilih Role Akun"
className="d-block btn-sm mb-2 w-100"
>
Pilih Role Akun
</Button>,
]}
<Button
key="Edit"
variant="outline-primary"
onClick={() => {
setShowModal(true);
setUsername(user.username);
}}
className="d-block btn-block btn-sm mb-2 w-100"
>
Edit
</Button>
<Button
key="Hapus"
variant="outline-danger"
onClick={() => {
handleDelete(user.username)}
}
disabled={loading}
className="d-block btn-block btn-sm mb-2 w-100"
>
Hapus
</Button>
</td>
</tr>
))}
</tbody>
{showModal ? (
<ModalEdit
show={handleShowModal}
onClose={handleCloseModal}
username={username}
/>
) : isDeleting ? ( <ModalConfirm
show={ isDeleting }
onHide= { () => { handleCloseModal(); setIsDeleting(false); } }
handleDelete={ handleDelete }
userToDelete={ username } />
) : null}
</Table>
);
};
export default TableUserInfo;
Question
How to fix the error and make data user is delete when admin click "yes" in modals ?
any help will be appreciated, thankyou.
Am new to React, and it feels like its very difficult to carry out mathematical calculations with react, Have been trying to add up two values gotten from firebase database but it keeps displaying the values as string and not adding the two values, Please I need help.
{contactObjects[id].gcc} + {contactObjects[id].lcc}
adding this two will only display all as string
E.g
if {contactObjects[id].gcc} is = 10 in firebase datebase and {contactObjects[id].lcc} as = 30
And adding + to the code wont sum up the two values, it will only display them as
10 + 30 which is in string and not 40
Please how can i go about it.
import React, { useState, useEffect } from "react";
import ContactForm from "./ContactForm";
import firebaseDb from "../firebase";
const Contacts = () => {
var [contactObjects, setContactObjects] = useState({});
var [currentId, setCurrentId] = useState("");
useEffect(() => {
firebaseDb.child("contacts").on("value", (snapshot) => {
if (snapshot.val() != null)
setContactObjects({
...snapshot.val(),
});
else setContactObjects({});
});
}, []); // similar to componentDidMount
const addOrEdit = (obj) => {
if (currentId == "")
firebaseDb.child("contacts").push(obj, (err) => {
if (err) console.log(err);
else setCurrentId("");
});
else
firebaseDb.child(`contacts/${currentId}`).set(obj, (err) => {
if (err) console.log(err);
else setCurrentId("");
});
};
const onDelete = (key) => {
if (window.confirm("Are you sure to delete this record?")) {
debugger;
firebaseDb.child(`contacts/${key}`).remove((err) => {
if (err) console.log(err);
else setCurrentId("");
});
}
};
return (
<>
<div className="jumbotron jumbotron-fluid">
<div className="container">
<h1 className="display-4 text-center">Contact Register</h1>
</div>
</div>
<div className="row">
<div className="col-md-5">
<ContactForm {...{ addOrEdit, currentId, contactObjects }} />
</div>
<div className="col-md-7">
<table className="table table-borderless table-stripped">
<thead className="thead-light">
<tr>
<th>Full Name</th>
<th>Mobile</th>
<th>Email</th>
<th>Address</th>
<th>Street</th>
<th>Address</th>
<th>Gcc</th>
<th>Lcc</th>
</tr>
</thead>
<tbody>
{Object.keys(contactObjects).map((id) => {
return (
<tr key={id}>
<td>{contactObjects[id].fullName}</td>
<td>{contactObjects[id].mobile}</td>
<td>{contactObjects[id].email}</td>
<td>{contactObjects[id].address}</td>
<td>{contactObjects[id].street}</td>
<td>{contactObjects[id].gcc}</td>
<td>{contactObjects[id].lcc}</td>
<td>
{contactObjects[id].gcc} +
{contactObjects[id].lcc}
</td>
<td>
<a
className="btn text-primary"
onClick={() => {
setCurrentId(id);
}}
>
<i className="fas fa-pencil-alt"></i>
</a>
<a
className="btn text-danger"
onClick={() => {
onDelete(id);
}}
>
<i className="far fa-trash-alt"></i>
</a>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
</>
);
};
export default Contacts;
If I understand correctly, then just parse these values to int. If in DB these are 'string'
{parseInt(contactObjects[id].gcc) + parseInt(contactObjects[id].lcc)}
I've added a search bar to my React-Firebase Dashboard.As a result, the search bar is displayed with the table of clients stored in Cloud Firestore, when I enter a text in the search bar It returns an empty table even if that word exists in the table.
PS: Both of the Results are shown below in screenshots
The table initially rendered
table after writing anything in the search bar
Customer.js
import React, { Fragment, useState } from "react";
import { Avatar } from '#material-ui/core';
import PageTitle from "../../../../layouts/PageTitle";
import { Dropdown, Table } from "react-bootstrap";
import { fire } from "../../../../../fire";
import { firestore } from "../../../../../fire";
import { collection, query, where } from "../../../../../fire";
import App from "../../../../../App";
export default class Recipe extends React.Component {
state = {
searchTerm : "",
Users: []
}
constructor(props){
super(props);
}
searchByTerm = (value) => {
this.setState({searchTerm : value});
}
componentDidMount() {
firestore.collection("Users").get().then((querySnapshot) => {
let User = []
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${doc.data().lastn}`);
User.push({
id : doc.id,
data: doc.data()})
});
this.setState({Users : User})
});
}
delete = (id) => {
console.log(id)
firestore.collection("Users").doc(id).delete().then(() => {
console.log("Document successfully deleted!");
this.props.history.push("#")
}).catch((error) => {console.error("Error removing document: ",
error);
});
}
render() {
return (
<Fragment>
<div className="col-12">
<div className="card">
<div className="card-header">
<div className="input-group search-area d-lg-inline-flex d-none mr-
5">
<input
type="text"
className="form-control"
placeholder="Search here"
onChange ={(e) => {
this.searchByTerm(e.target.value);
}}
/>
<div className="input-group-append">
<span className="input-group-text"
>
<svg
width={20}
height={20}
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M23.7871 22.7761L17.9548 16.9437C19.5193 15.145 20.4665 12.7982 20.4665 10.2333C20.4665 4.58714 15.8741 0 10.2333 0C4.58714 0 0 4.59246 0 10.2333C0 15.8741 4.59246 20.4665 10.2333 20.4665C12.7982 20.4665 15.145 19.5193 16.9437 17.9548L22.7761 23.7871C22.9144 23.9255 23.1007 24 23.2816 24C23.4625 24 23.6488 23.9308 23.7871 23.7871C24.0639 23.5104 24.0639 23.0528 23.7871 22.7761ZM1.43149 10.2333C1.43149 5.38004 5.38004 1.43681 10.2279 1.43681C15.0812 1.43681 19.0244 5.38537 19.0244 10.2333C19.0244 15.0812 15.0812 19.035 10.2279 19.035C5.38004 19.035 1.43149 15.0865 1.43149 10.2333Z"
fill="#A4A4A4"
/>
</svg>
</span>
</div> </div>
<h4 className="card-title">Customer List </h4>
</div>
<div className="card-body">
<Table responsive className="w-100">
<div id="example_wrapper" className="dataTables_wrapper">
<table id="example" className="display w-100 dataTable">
<thead>
<tr role="row">
<th>Avatar</th>
<th>Email</th>
<th>Firstname</th>
<th>Lastname</th>
<th>PhoneNumber</th>
{/* <th className="pl-5 width200">
Billing Address
</th> */}
<th>Action</th>
</tr>
</thead>
<tbody>
{this.state.Users.filter( (val) =>{
const { email = "", firstname = "" } = val;
// console.log(this.state.searchTerm);
if (this.state.searchTerm === "") {
return val;
} else if (
email.toLowerCase().includes(this.state.searchTerm.toLowerCase()) ||
firstname.toLowerCase().includes(this.state.searchTerm.toLowerCase())
) {
return val;
}
}).map(data => {
return (
<tr>
<td> <Avatar className ="rounded-circle img-fluid" src={data.data.avatar}/> </td>
<td>{data.data.email}</td>
<td>{data.data.firstname}</td>
<td>{data.data.datalastname}</td>
<td>{data.data.phonenumber}</td>
<td>
<div
className="btn btn-danger shadow btn-xs sharp" onClick ={this.delete.bind(this, data.id)}
>
<i className="fa fa-trash"></i> </div></td>
</tr>
);
})}
</tbody>
</table>
</div>
</Table>
</div>
</div>
</div>
</Fragment>
);
};
};
Array.prototype.filter callback should be returning a boolean, not the element being iterated over.
This is how I suggest rewriting your filter function: if there is no search term (i.e. falsey) then return true to indicate all elements iterated over should be return, otherwise, return the result of the comparison.
const { Users, searchTerm } = this.state;
const term = this.state.searchTerm.toLowerCase();
...
Users.filter((val) => {
const { data: { email = "", firstname = "" } = {} } = val;
if (term) {
return (
email.toLowerCase().includes(term) ||
firstname.toLowerCase().includes(term)
);
}
return true;
})
A slightly more succinct version could be written as follows:
const { Users, searchTerm } = this.state;
const term = this.state.searchTerm.toLowerCase();
...
Users.filter(({ data: { email = "", firstname = "" } = {} }) =>
term ? email.concat(firstname).toLowerCase().includes(term) : true
)
Update
After you've stated that you implemented my suggestions and it's still not working I took a closer look at what you are rendering and noticed that in the .map callback you reference each field (email, firstname, etc...) from a data property on each element. Since it seems you are able to render your data when no filter is being applied I'll assume this structure to be correct. As such then, the .filter callback needs to also reference the nested field properties from a data property. I've updated the above code snippets.
I am listing data with api.
I show the data I received to the user with reactstrap table.
but I want to paging.
Up to 6 records are displayed on one page, other records are displayed on the following pages.
import React, { Component, useState } from "react";
import withAuth from "../../components/helpers/withAuth";
import {
Button,
Card,
CardBody,
CardHeader,
Col,
Pagination,
PaginationItem,
PaginationLink,
Row,
Table,
} from "reactstrap";
class CustomerDebt extends Component {
constructor(props) {
super(props);
this.domain = `http://127.0.0.1:8000`;
this.state = {
isLoaded: true,
items: [], //Customer Debt Items
};
}
async componentDidMount() {
//customer debt list
await fetch(
`${this.domain}/api/debt/list?customer=` +
this.props.customerInfo.customer.id,
{
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
"Content-Type": "application/json"
}
}
)
.then(res => {
if (res.ok) {
return res.json();
} else {
return res.json().then(err => Promise.reject(err));
}
})
.then(json => {
this.setState({
items: json,
});
this.abortController.abort();
})
.catch(error => {
return error;
});
}
render() {
const { isLoaded, items } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className={"animated fadeIn container-fluid"}>
<Row>
<Col>
<Card>
<CardHeader>
<i className="fa fa-align-justify" /> Müşteri Borcu
</CardHeader>
<CardBody>
<Table hover bordered striped responsive size="sm">
<thead>
<tr>
<th width={"10"} />
<th width={"15"}>No</th>
<th style={{ display: "none" }}>User</th>
<th style={{ display: "none" }}>Key</th>
<th style={{ display: "none" }}>CreatedUserKey</th>
<th width={"40"}>Total debt</th>
<th width={"40"}>Received amount</th>
<th scope={"row"}>Description</th>
<th width={"20"}>Payment Date</th>
</tr>
</thead>
<tbody>
{items.map(item => {
return (
<tr key={item.id}>
<td>{item.id}</td>
<td style={{ display: "none" }}>{item.user}</td>
<td style={{ display: "none" }}>{item.debtKey}</td>
<td style={{ display: "none" }}> {" "} {item.createduserKey}{" "} </td>
<td>{item.totalDebt}</td>
<td>{item.receivedAmount}</td>
<td>{item.description}</td>
<td> {new Date(item.paymentDate).toLocaleString()} </td>
</tr>
);
})}
</tbody>
</Table>
<nav>
<Pagination>
<PaginationItem>
<PaginationLink previous tag="button">
Back
</PaginationLink>
</PaginationItem>
<PaginationItem active>
<PaginationLink tag="button">1</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationLink tag="button">2</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationLink tag="button">3</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationLink tag="button">4</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationLink next tag="button">
Next
</PaginationLink>
</PaginationItem>
<PaginationItem></PaginationItem>
</Pagination>
</nav>
</CardBody>
</Card>
</Col>
</Row>
</div>
);
}
}
}
export default CustomerDebt;
You need to generate pagination buttons dynamically based on number of records and then on pressing pagination button, set the page number and create an array if items that you want to show based on page number and per page size.
This is sample code to give you an idea how to get this done. This is not complete or bug proof since it is your job. I hope will get the idea.
class CustomerDebt extends Component {
constructor(props) {
super(props);
this.domain = `http://127.0.0.1:8000`;
this.state = {
isLoaded: true,
items: [], //Customer Debt Items,
pageItems: [],
page: 0,
pageSize: 6
};
}
async componentDidMount() {
const { pageSize } = this.state;
//customer debt list
await fetch(
`${this.domain}/api/debt/list?customer=` +
this.props.customerInfo.customer.id,
{
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
"Content-Type": "application/json"
}
}
)
.then(res => {
if (res.ok) {
return res.json();
} else {
return res.json().then(err => Promise.reject(err));
}
})
.then(json => {
this.setState({
items: json,
pageItems: json.slice(0, pageSize)
});
this.abortController.abort();
})
.catch(error => {
return error;
});
}
render() {
const { isLoaded, pageItems, items, page, pageSize } = this.state;
const pages = Math.ceil(items.length / page);
const paginationItems = Array(pages).fill('').map((i, index) => (
<PaginationItem active={page === index}>
<PaginationLink tag="button" onClick={() => this.setState({page: index })}}>2</PaginationLink>
</PaginationItem>
));
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className={"animated fadeIn container-fluid"}>
<Row>
<Col>
<Card>
<CardHeader>
<i className="fa fa-align-justify" /> Müşteri Borcu
</CardHeader>
<CardBody>
<Table hover bordered striped responsive size="sm">
<thead>
<tr>
<th width={"10"} />
<th width={"15"}>No</th>
<th style={{ display: "none" }}>User</th>
<th style={{ display: "none" }}>Key</th>
<th style={{ display: "none" }}>CreatedUserKey</th>
<th width={"40"}>Total debt</th>
<th width={"40"}>Received amount</th>
<th scope={"row"}>Description</th>
<th width={"20"}>Payment Date</th>
</tr>
</thead>
<tbody>
{pageItems.map(item => {
return (
<tr key={item.id}>
<td>{item.id}</td>
<td style={{ display: "none" }}>{item.user}</td>
<td style={{ display: "none" }}>{item.debtKey}</td>
<td style={{ display: "none" }}> {" "} {item.createduserKey}{" "} </td>
<td>{item.totalDebt}</td>
<td>{item.receivedAmount}</td>
<td>{item.description}</td>
<td> {new Date(item.paymentDate).toLocaleString()} </td>
</tr>
);
})}
</tbody>
</Table>
<nav>
<Pagination>
<PaginationItem onClick={() => this.setState(prev => ({page: prev.page -1}))}>
<PaginationLink>
Back
</PaginationLink>
<PaginationItem onClick={() => this.setState(prev => ({page: prev.page + 1}))}>
<PaginationLink next tag="button">
Next
</PaginationLink>
</PaginationItem>
<PaginationItem></PaginationItem>
</Pagination>
</nav>
</CardBody>
</Card>
</Col>
</Row>
</div>
);
}
}
}
export default CustomerDebt;
First of all you need to create two variables that will help you to track current page and size of the table. Let's call them pageSize and pageIndex
class App extends React.Component {
state = {
pageSize: 2, // <- 2 items will be shown on single page
pageIndex: 0, // 0 is a default page to show
items: []
};
...
Then you need to fetch some data from the external source. In my example, I just create a mock array and set it to the state.
...
componentDidMount() {
const data = [
{ id: 1, name: "Roman" },
{ id: 2, name: "Oleh" },
{ id: 3, name: "Vitalii" },
{ id: 4, name: "Mikhail" },
{ id: 5, name: "Vladislav" },
{ id: 6, name: "Anton" },
{ id: 7, name: "Yurii" },
{ id: 8, name: "Volodymir" },
{ id: 9, name: "Taras" }
];
this.setState({ items: data });
}
...
After that, you need to create helper functions and place table navigation logic there. Let's name them handlePrevPageClick and handleNextPageClick.
The handlePrevPageClick should decrease current index on click. Also, we need to prevent user from scrolling to much. So, if pageIndex is not 0 - decrease, otherwise stop decreasing.
The handleNextPageClick should have absolutely the same logic as handlePrevPageClick. The only thing it is reversed. Don't let user overscroll your table. To do that, we need to understand how many pages do we have. By dividing this.state.items / this.state.pageSize we will get the total number of available pages. Let's imagine that our table have 12 items and page size is 5. So, 12 / 5 = 2.4. It means that we will have 2 pages full loaded and 4 items left. By using Math.ceil(12 / 5) we will get 3 - is an integer number of total available pages of the table. After that, we just add simple condition, if pageIndex < 3, if yes - increase pageIndex, otherwise stop.
...
handlePrevPageClick(event) {
this.setState(prevState => ({
pageIndex: prevState.pageIndex > 0 ? prevState.pageIndex - 1 : 0
}));
}
handleNextPageClick(event) {
this.setState(prevState => ({
pageIndex:
prevState.pageIndex <
Math.ceil(prevState.items.length / prevState.pageSize)
? prevState.pageIndex + 1
: prevState.pageIndex
}));
}
The last think is to render your table with correct rows. To do that, you can use .slice(...). First argument is a left boundary of the page, the second one is a right boundary of the page.
First page
this.state.pageIndex * this.state.pageSize, // 0 * 5 = 0
this.state.pageIndex * this.state.pageSize + this.state.pageSize // 0 * 5 + 5 = 5
To show elements from index 0 to 5.
Second page
this.state.pageIndex * this.state.pageSize, // 1 * 5 = 5
this.state.pageIndex * this.state.pageSize + this.state.pageSize // 1 * 5 + 5 = 10
To show elements from index 5 to 10.
...
render() {
return (
<>
<button onClick={event => this.handlePrevPageClick(event)}>
Prev page
</button>
<button onClick={event => this.handleNextPageClick(event)}>
Next page
</button>
<table border="1">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{this.state.items
.slice(
this.state.pageIndex * this.state.pageSize,
this.state.pageIndex * this.state.pageSize + this.state.pageSize
)
.map(item => (
<tr>
<td>{item.id}</td>
<td>{item.name}</td>
</tr>
))}
</tbody>
</table>
</>
);
}
}
If you want to see full working example, please use this CodeSandbox link
I have a problem. I'm lost in the deep forest of reactJs. I'm new here.
I have 8 components which I need to get via clicking on short-name button .
What are the steps.
I select what I need from the first filter and I get short_names and all the components without data.
I don't want to get all the components, i need just 1 component that I'll get by clicking on a short name.
Screenshot here
Here is code of rendering page:
import React, { Component } from 'react';
import { Link } from 'react-router';
import { getAll, getAllRates } from '../actions';
import { MODULE_NAME } from './index';
import { PanelHeader, PanelFooter, LocalFilter } from 'Components';
import locales from 'Shared/locales';
import search from 'Shared/search';
import sortBy from 'Shared/sortBy';
import { AvsProviders, FakProviders, LaaProviders, Laac1Providers,
Laac2Providers, Laac3Providers, MpgProviders, Mpg2Providers } from '../ComponentsProviders';
export default class ListsAccounting extends Component {
state = {
data: [],
le_id: null,
year: new Date().getFullYear(),
totalPages: 0,
searchString: '',
limit: '50',
page: 1,
};
search = search(this);
sortBy = sortBy(this);
loadData = (params) => {
const { searchString } = this.state;
const q = searchString === '' ? null : searchString;
getAll({ leId: this.state.le_id, name: MODULE_NAME, params: { q, year: this.state.year, ...params } })
.then(success => this.setState({
data: success.data,
totalPages: success.totalPages,
page: success.page,
limit: String(success.limit || ''),
}));
};
constructor() {
super();
this.onClick = this.handleClick.bind(this);
}
handleClick(event) {
const { id } = event.target;
console.log(id);
}
getData = (leId, id, type, year) => {
getAllRates({ leId, id, type, year, name: MODULE_NAME })
.then(() => this.loadData());
};
changeState = state => this.setState(state, () => this.loadData());
render() {
const { limit, totalPages, data } = this.state;
console.log(this);
return (
<div className="container">
<div className="row">
<div className="col-xs-12 col-sm-12 col-md-6">
<div className="panel panel-adminme table-dynamic">
<PanelHeader
name="insurances"
currentState={{
state: this.state,
loadData: this.loadData,
}}
/>
<div className="table-filters">
<div className="row no-x-margin">
<div className="col-sm-4 col-xs-6">
<LocalFilter
name="all-providers-leg-entities"
placeholder="le_id"
option="le_id"
value={this.state.le_id}
changeState={this.changeState}
/>
</div>
<div className="col-md-3 col-sm-4 col-xs-6">
<LocalFilter
name="insurance-years"
placeholder="year"
option="year"
value={this.state.year}
changeState={this.changeState}
/>
</div>
</div>
</div>
<div className="table-responsive">
<table className="table table-bordered table-striped table-hover">
<thead>
<tr className="text-center">
<th>
NAME
</th>
<th>
SHORT_NAME
</th>
<th>
ACTION
</th>
</tr>
</thead>
<tbody>
{
!data.length &&
<tr>
<td colSpan="3" className="text-center">
{locales('no_rows')}
</td>
</tr>
}
{
data.map((row, index) => (
<tr key={`${MODULE_NAME}-${index}`}>
<td>
<h5>{row.type}</h5>
</td>
<td>
{
row.text.map((name, indexText) => (
<span key={name} className="margin-right-10">
<Link
key={row.type}
role="button"
onClick={ () => this.getData(
this.state.le_id,
row.text_id[indexText],
row.type,
row.year,
)}
>
{name}
</Link>
</span >
))
}
</td>
<td className="btn btn-info">
ADD
</td>
</tr>
))
}
</tbody>
</table>
</div>
<PanelFooter
limit={limit}
totalPages={totalPages}
loadData={this.loadData}
/>
</div>
</div>
<div className="col-xs-12 col-sm-12 col-md-6">
{ data.type === data.type && data.text_id === data.text_id &&
data.map((row) => {
console.log(row.type);
switch (row.type) {
case 'AVS':
return (
<AvsProviders/>
);
case 'FAK' :
return (
<FakProviders/>
);
case 'LAA':
return (
<LaaProviders/>
);
case 'LAAC1':
return (
<Laac1Providers/>
);
case 'LAAC2':
return (
<Laac2Providers/>
);
case 'LAAC3':
return (
<Laac3Providers/>
);
case 'MPG':
return (
<MpgProviders/>
);
case 'MPG2':
return (
<Mpg2Providers/>
);
default:
return null;
}
})
}
</div>
</div>
</div>
);
}
}
Here is page of 1 of the rendering components:
import React, { Component } from 'react';
import { getAllRates } from '../../actions';
import { PanelHeader } from 'Components';
const MODULE_NAME = 'FAK';
export default class FakProviders extends Component {
state = {
data: [],
le_id: null,
year: new Date().getFullYear(),
totalPages: 0,
searchString: '',
limit: '50',
page: 1,
};
componentDidMount() {
this.loadData();
}
loadData = (params) => {
const { searchString } = this.state;
const q = searchString === '' ? null : searchString;
getAllRates({ leId: this.props.params.le_id,
id: this.props.params.text_id,
name: MODULE_NAME,
params: { q, ...params } })
.then(success => this.setState({
data: success.data,
totalPages: success.totalPages,
page: success.page,
limit: String(success.limit || ''),
}));
};
changeState = state => this.setState(state, () => this.loadData());
render() {
const { data } = this.state;
return (
<div className="panel panel-adminme table-dynamic">
<PanelHeader
name="insurances"
currentState={{
search: this.search,
state: this.state,
loadData: this.loadData,
}}
/>
<div className="table-responsive">
<table className="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>
<h4>{data.fak_short_name}</h4>
</th>
<th>
<h4>{data.year}</h4>
</th>
</tr>
</thead>
<tbody>
<tr>
<th>
<h4>fak_rate_ee</h4>
</th>
<th>
<h4>
{data.fak_rate_ee}
</h4>
</th>
</tr>
<tr>
<th>
<h4>fak_rate_er</h4>
</th>
<th>
<h4>
{data.fak_rate_er}
</h4>
</th>
</tr>
</tbody>
</table>
</div>
<div className="panel-footer" />
</div>
);
}
}