I'm trying to achieve adding edit and delete button via MUI Datatable it's already applied but whenever I pressed the edit button the URL says the undefined. Here is an image and my code. Thanks for your help really appreciate it.
as you can see it says /client/edit/undefined whereas should be an id
Code:
import React, { Component } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import MUIDataTable from "mui-datatables";
const Client = (props) => (
<>
<Link to={"client/edit/" + props.client._id} className="btn btn-primary">
Edit
</Link>
<a
href="client"
onClick={() => {
props.deleteClient(props.client._id);
}}
className="btn btn-danger"
>
Delete
</a>
</>
);
export default class ClientsList extends Component {
constructor(props) {
super(props);
this.deleteClient = this.deleteClient.bind(this);
this.state = { clients: [] };
}
componentDidMount() {
axios
.get("http://localhost:5000/clients/")
.then((response) => {
this.setState({ clients: response.data });
})
.catch((error) => {
console.log(error);
});
}
deleteClient(id) {
axios.delete("http://localhost:5000/clients/" + id).then((response) => {
console.log(response.data);
});
this.setState({
clients: this.state.clients.filter((el) => el._id !== id),
});
}
clientList(currentclient) {
return (
<Client
client={currentclient}
deleteClient={this.deleteClient}
key={currentclient[0]}
/>
);
}
render() {
const columns = [
{
name: "_id",
options: {
display: false,
},
},
{
name: "name",
label: "Name",
options: {
filter: true,
sort: true,
},
},
{
name: "address",
label: "Address",
options: {
filter: true,
sort: true,
},
},
{
name: "mobile",
label: "Mobile",
options: {
filter: true,
sort: true,
},
},
{
name: "email",
label: "Email",
options: {
filter: true,
sort: true,
},
},
{
name: "gender",
label: "Gender",
options: {
filter: true,
sort: true,
},
},
{
name: "birthday",
label: "Birthday",
options: {
filter: true,
sort: true,
},
},
{
name: "facebookPage",
label: "Facebook Page",
options: {
filter: true,
sort: true,
},
},
{
name: "facebookName",
label: "Facebook Name",
options: {
filter: true,
sort: true,
},
},
{
name: "existing",
label: "Existing",
options: {
filter: true,
sort: true,
},
},
{
name: "remarks",
label: "Remarks",
options: {
filter: true,
sort: true,
},
},
{
name: "Action",
options: {
customBodyRender: (value, tableMeta, updateValue) => {
return <>{this.clientList(tableMeta.rowData)}</>;
},
},
},
];
const { clients } = this.state;
return (
<>
<br />
<br />
<br />
<div style={{ margin: "10px 15px", overflowX: "auto" }}>
<Link to={"client/create/"} className="btn btn-primary pull-right">
Add Client Data
</Link>
<br />
<br />
<br />
<MUIDataTable data={clients} columns={columns} />
</div>
</>
);
}
}
Everyone, the Table data is transposed into an array, this is my code if you wanted to have a edit and delete button using mui datatables.
import React, { Component } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import MUIDataTable from "mui-datatables";
const Client = (props) => (
<>
{console.log("Client Props", props)}
<Link to={"client/edit/" + props.client[0]} className="btn btn-primary">
Edit
</Link>
<a
href="client"
onClick={() => {
props.deleteClient(props.client[0]);
}}
className="btn btn-danger"
>
Delete
</a>
</>
);
export default class ClientsList extends Component {
constructor(props) {
super(props);
this.deleteClient = this.deleteClient.bind(this);
this.state = { clients: [] };
}
componentDidMount() {
axios
.get("http://localhost:5000/clients/")
.then((response) => {
this.setState({ clients: response.data });
})
.catch((error) => {
console.log(error);
});
}
deleteClient(id) {
axios.delete("http://localhost:5000/clients/" + id).then((response) => {
console.log(response.data);
});
this.setState({
clients: this.state.clients.filter((el) => el._id !== id),
});
}
clientList(currentclient) {
return (
<Client
client={currentclient}
deleteClient={this.deleteClient}
key={currentclient[0]}
/>
);
}
render() {
const columns = [
{
name: "_id",
options: {
display: false,
},
},
{
name: "name",
label: "Name",
options: {
filter: true,
sort: true,
},
},
{
name: "address",
label: "Address",
options: {
filter: true,
sort: true,
},
},
{
name: "mobile",
label: "Mobile",
options: {
filter: true,
sort: true,
},
},
{
name: "email",
label: "Email",
options: {
filter: true,
sort: true,
},
},
{
name: "gender",
label: "Gender",
options: {
filter: true,
sort: true,
},
},
{
name: "birthday",
label: "Birthday",
options: {
filter: true,
sort: true,
},
},
{
name: "facebookPage",
label: "Facebook Page",
options: {
filter: true,
sort: true,
},
},
{
name: "facebookName",
label: "Facebook Name",
options: {
filter: true,
sort: true,
},
},
{
name: "existing",
label: "Existing",
options: {
filter: true,
sort: true,
},
},
{
name: "remarks",
label: "Remarks",
options: {
filter: true,
sort: true,
},
},
{
name: "Action",
options: {
customBodyRender: (value, tableMeta, updateValue) => {
return <>{this.clientList(tableMeta.rowData)}</>;
},
},
},
];
const { clients } = this.state;
return (
<>
<br />
<br />
<br />
<div style={{ margin: "10px 15px", overflowX: "auto" }}>
<Link to={"client/create/"} className="btn btn-primary pull-right">
Add Client Data
</Link>
<br />
<br />
<br />
<MUIDataTable data={clients} columns={columns} />
</div>
</>
);
}
}
Related
I have a filter dropdown in the header and when users apply the filters I want to run the assigned function according to their choices but I couldn't run it, I got "... is not a function" error.
Also, even if I solve this problem, I will probably have problems in applying more than one filter at the same time, I would be very grateful if anyone could offer a solution in the form of applying filters in multiple ways.
Example Object:
const filters = [
{
section: 'Call Types',
slug: 'call-types',
type: 'multiselect',
options: [
{
label: 'Inbound',
slug: 'inbound',
value: true,
func: (data) =>
data.items.filter((item) => {
return item.className === 'ib'
}),
},
{
label: 'Outbound',
slug: 'outbound',
value: true,
func: (data) =>
data.items.filter((item) => {
return item.className === 'ob'
}),
},
],
},
{
section: 'Data Types',
slug: 'data-types',
type: 'multiselect',
options: [
{
label: 'Sentiment',
slug: 'sentiment',
value: false,
func: (data) =>
data.items.filter((item) => {
return item.d1 === 1
}),
},
{
label: 'Capture Fails',
slug: 'capture-fails',
value: false,
func: (data) =>
data.items.filter((item) => {
return item.d2 > 0.5
}),
},
{
label: 'Audio Notes',
slug: 'audio-notes',
value: false,
func: (data) =>
data.items.filter((item) => {
return item.d1 === 1 && item.d2 > 0.5
}),
},
],
},
{
section: 'Others',
slug: 'others',
type: 'singleselect',
options: [
{
label: 'Show All Agents',
slug: 'show-all-agents',
value: true,
func: (data) =>
data.items.filter((item) => {
return item
}),
},
],
},
]
exports.filters = filters
And here is the method I'm trying to run when users click to "Filter" button.
Timeline vue file:
<template>
<vis-timeline
:groups="filteredData.groups"
:items="filteredData.items"
/>
</template>
<script>
import { mapActions, mapState } from 'vuex'
import VisTimeline from '~/components/UI/VisTimeline.vue'
export default {
components: { VisTimeline },
computed: {
...mapState({
callTimeline: (state) => state.agents.callTimeline,
timelineLoading: (state) => state.agents.loading,
filterOption: (state) => state.agents.filterOption,
}),
filteredData() {
var filtered = Object.assign(
{},
JSON.parse(JSON.stringify(this.callTimeline))
)
return this.filterItems(filtered)
},
},
methods: {
filterItems(data) {
if (this.filterOption) {
this.filterOption.forEach((filter) => {
filter.options.some((option) => {
if (option.value) {
return option.func(data)
}
})
})
}
return data
}
}
}
</script>
Header vue file:
<template>
<a-layout-header style="background: #fff; padding: 0">
<a-dropdown
:trigger="['click']"
:visible="visible"
#visibleChange="handleVisible"
>
<template #overlay>
<a-menu>
<a-menu-item-group
v-for="filter in filters"
:key="filter.slug"
:title="filter.section"
>
<a-menu-item :key="filter.slug">
<a-checkbox
v-for="option in filter.options"
:key="option.slug"
:name="option.slug"
:checked="option.value"
#change="filterChanges"
>
{{ option.label }}
</a-checkbox>
</a-menu-item>
</a-menu-item-group>
<a-menu-divider />
<a-menu-item key="buttons"
><div class="flex justify-between">
<a-button #click="visible = false" type="danger" ghost
>Cancel</a-button
>
<a-button #click="applyFilters" type="primary">Filter</a-button>
</div></a-menu-item
>
</a-menu>
</template>
<div class="mb-1">
<a-button type="primary">
<div class="flex flex-row justify-center space-x-2 items-center">
<a-icon type="filter" />
<span>Filters</span>
<a-icon type="down" />
</div>
</a-button>
</div>
</a-dropdown>
</a-layout-header>
</template>
<script>
import { mapActions} from 'vuex'
import { filters } from '~/utils/Filters'
export default {
name: 'DBHeader',
data() {
return {
visible: false,
filters: filters,
}
},
methods: {
...mapActions({
setFilterOption: 'agents/setFilterOption',
}),
handleVisible(flag) {
this.visible = flag
},
filterChanges(e) {
this.filters.forEach((filter) => {
filter.options.some((option) => {
if (option.slug === e.target.name) {
option.value = e.target.checked
}
})
})
},
applyFilters() {
var filters = Object.assign([], JSON.parse(JSON.stringify(this.filters)))
this.setFilterOption(filters)
this.visible = false
},
},
}
</script>
Hi Everyone, I'm trying to achieve adding edit and delete button in ReactJS using Mui Datatable, but the problem is that it keeps on repeating because of the Map sorry I'm just new in ReactJS anyways, here is my image and my code:
This is an example of my image:
And This My Code:
import React, { Component } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import MUIDataTable from "mui-datatables";
const Client = (props) => (
<>
<Link to={"client/edit/" + props.client._id} className="btn btn-primary">
Edit
</Link>
<a
href="client"
onClick={() => {
props.deleteClient(props.client._id);
}}
className="btn btn-danger"
>
Delete
</a>
</>
);
export default class ClientsList extends Component {
constructor(props) {
super(props);
this.deleteClient = this.deleteClient.bind(this);
this.state = { clients: [] };
}
componentDidMount() {
axios
.get("http://localhost:5000/clients/")
.then((response) => {
this.setState({ clients: response.data });
})
.catch((error) => {
console.log(error);
});
}
deleteClient(id) {
axios.delete("http://localhost:5000/clients/" + id).then((response) => {
console.log(response.data);
});
this.setState({
clients: this.state.clients.filter((el) => el._id !== id),
});
}
// This is the map I was talking about:
clientList() {
return this.state.clients.map((currentclient) => {
return (
<Client
client={currentclient}
deleteClient={this.deleteClient}
key={currentclient._id}
/>
);
});
}
render() {
const columns = [
{
name: "name",
label: "Name",
options: {
filter: true,
sort: true,
},
},
{
name: "address",
label: "Address",
options: {
filter: true,
sort: true,
},
},
{
name: "mobile",
label: "Mobile",
options: {
filter: true,
sort: true,
},
},
{
name: "email",
label: "Email",
options: {
filter: true,
sort: true,
},
},
{
name: "gender",
label: "Gender",
options: {
filter: true,
sort: true,
},
},
{
name: "birthday",
label: "Birthday",
options: {
filter: true,
sort: true,
},
},
{
name: "facebookPage",
label: "Facebook Page",
options: {
filter: true,
sort: true,
},
},
{
name: "facebookName",
label: "Facebook Name",
options: {
filter: true,
sort: true,
},
},
{
name: "existing",
label: "Existing",
options: {
filter: true,
sort: true,
},
},
{
name: "remarks",
label: "Remarks",
options: {
filter: true,
sort: true,
},
},
{
name: "Action",
options: {
customBodyRender: () => {
return <>{this.clientList()}</>;
},
},
},
];
const { clients } = this.state;
return (
<>
<br />
<br />
<br />
<div style={{ margin: "10px 15px", overflowX: "auto" }}>
<Link to={"client/create/"} className="btn btn-primary pull-right">
Add Client Data
</Link>
<br />
<br />
<br />
<MUIDataTable data={clients} columns={columns} />
</div>
</>
);
}
}
Thank you for your help and understanding I really appreciate it!
You can just not use map in the clientList() function because you are returning (edit, delete ) of all the clients for each row in the table. you also can pass the row data like I will show in the link on each button and have the _id as a hidden column on your table so that you can have access on it.
import React, { Component } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import MUIDataTable from "mui-datatables";
const Client = (props) => (
<>
<Link to={"client/edit/" + props.client._id} className="btn btn-primary">
Edit
</Link>
<a
href="client"
onClick={() => {
props.deleteClient(props.client._id);
}}
className="btn btn-danger"
>
Delete
</a>
</>
);
export default class ClientsList extends Component {
constructor(props) {
super(props);
this.deleteClient = this.deleteClient.bind(this);
this.state = {
clients: [{
}]
};
}
componentDidMount() {
axios
.get("http://localhost:5000/clients/")
.then((response) => {
this.setState({ clients: response.data });
})
.catch((error) => {
console.log(error);
});
}
deleteClient(id) {
axios.delete("http://localhost:5000/clients/" + id).then((response) => {
console.log(response.data);
});
this.setState({
clients: this.state.clients.filter((el) => el._id !== id),
});
}
// This is the map I was talking about:
clientList(currentclient) {
// current cleint her is an array that contain all the columns values for the row specify
// assuming that _id will be the first column
return (
<Client
client={currentclient}
deleteClient={this.deleteClient}
key={currentclient[0]}
/>
);
}
render() {
const columns = [
{
name: "_id",
options: {
display: false,
}
},
{
name: "name",
label: "Name",
options: {
filter: true,
sort: true,
},
},
{
name: "address",
label: "Address",
options: {
filter: true,
sort: true,
},
},
{
name: "mobile",
label: "Mobile",
options: {
filter: true,
sort: true,
},
},
{
name: "email",
label: "Email",
options: {
filter: true,
sort: true,
},
},
{
name: "gender",
label: "Gender",
options: {
filter: true,
sort: true,
},
},
{
name: "birthday",
label: "Birthday",
options: {
filter: true,
sort: true,
},
},
{
name: "facebookPage",
label: "Facebook Page",
options: {
filter: true,
sort: true,
},
},
{
name: "facebookName",
label: "Facebook Name",
options: {
filter: true,
sort: true,
},
},
{
name: "existing",
label: "Existing",
options: {
filter: true,
sort: true,
},
},
{
name: "remarks",
label: "Remarks",
options: {
filter: true,
sort: true,
},
},
{
name: "Action",
options: {
customBodyRender: (value, tableMeta, updateValue) => {
return <>{this.clientList(tableMeta.rowData)}</>;
},
},
},
];
const { clients } = this.state;
return (
<>
<br />
<br />
<br />
<div style={{ margin: "10px 15px", overflowX: "auto" }}>
<Link to={"client/create/"} className="btn btn-primary pull-right">
Add Client Data
</Link>
<br />
<br />
<br />
<MUIDataTable data={clients} columns={columns} />
</div>
</>
);
}
}
you can deconstruct clients data from state and then pass it to MUIDataTable
const { clients } = this.state;
const rows = clients.map((client) => {
return {
// assuming atributes
name: client.name,
address: client.address,
mobile: client.mobile,
email: client.email,
gender: client.gender,
birthday: client.birthday,
action: <Link to=`client/edit/${client.id}` calssName='btn btn-primary'> Edit </Link> <a href='client' onClick={() => this.deleteClient(client.id)}> delete </a>
}
}
and then pass it in data props in MUIDataTable
<MUIDataTable data={rows} columns={columns} />
this is an example of a working snippet, tweak it to match you need
const rows = orders.map((order) => {
return {
ref: <Link to={"/orders/" + order.ref}>{order.ref.slice(0, 8)}</Link>,
amount: order.amount,
donated: order.ticketsDetails[0].ticketDonate != "" ? "Yes" : "No",
date: order.createdAt.slice(0, 16),
};
});
const columns = [
{
label: "Ref",
name: "ref",
options: {
filter: true,
sort: true,
},
},
{
label: "Amount",
name: "amount",
options: {
filter: true,
sort: true,
},
},
{
label: "Date",
name: "date",
options: {
filter: true,
sort: true,
},
},
{
label: "Donated",
name: "donated",
options: {
filter: true,
sort: true,
},
},
];
return (
<div className="orders-container">
<MUIDataTable columns={columns} data={rows} />
</div>
);
I have an existing table wherein I used a library called react-bootstrap-table-next
It serves its purpose of showing data in a table in which the values are from a JSON response
However, I want to add an Action column containing edit and delete
I want to achieve this using material-ui icons
Any advice as to how should I start? Should I fully convert my table first into material-ui to achieve this?
OR I can just edit profiles state array and map it into a new array containing icons?
ProfileMaintenance.js
const [profiles, setProfiles] = useState([]); // populate table with saved profiles
const retrieveProfiles = useCallback(() => {
ProfileMaintenanceService.retrieveProfiles()
.then((response) => {
console.log(
"ProfileMaintenance - retrieveProfiles response.data >>> ",
response.data
);
setProfiles(response.data);
})
.catch((error) => {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers); // send to logger
if (
error.response.data.error !== undefined &&
error.response.data.error != ""
) {
store.addNotification({
...notification,
type: "danger",
message: error.response.data.error,
dismiss: {
duration: 5000,
},
});
} else {
store.addNotification({
...notification,
type: "danger",
message:
"Server responded with a status code that falls out of the range of 2xx",
dismiss: {
duration: 5000,
},
});
}
} else if (error.request) {
// if API is down
console.log(error.request); // send to logger
store.addNotification({
...notification,
type: "danger",
message: "Request was made but no response was received",
dismiss: {
duration: 5000,
},
});
}
});
});
const columnsProfile = [
// {
// headerStyle: {
// backgroundColor: '#b3b3b3'
// },
// dataField: 'id', // for dev only
// text: 'ID',
// sort: true
// },
{
headerStyle: {
backgroundColor: "#b3b3b3",
},
dataField: "profileName",
text: "Name",
sort: true,
filter: textFilter(),
},
{
headerStyle: {
backgroundColor: "#b3b3b3",
},
dataField: "createdBy",
text: "Creator",
sort: true,
},
{
headerStyle: {
backgroundColor: "#b3b3b3",
},
dataField: "creationDate",
text: "Creation Date",
sort: true,
// filter: dateFilter()
},
{
headerStyle: {
backgroundColor: "#b3b3b3",
},
dataField: "lastModifier",
text: "Last Modifier",
sort: true,
},
{
headerStyle: {
backgroundColor: "#b3b3b3",
},
dataField: "lastModification",
text: "Last Modification",
sort: true,
},
{
headerStyle: {
backgroundColor: "#b3b3b3",
},
dataField: "action",
text: "Action",
},
];
const options = {
paginationSize: 4,
pageStartIndex: 1,
alwaysShowAllBtns: true,
hideSizePerPage: true,
firstPageText: "First",
prePageText: "Back",
nextPageText: "Next",
lastPageText: "Last",
nextPageTitle: "First page",
prePageTitle: "Pre page",
firstPageTitle: "Next page",
lastPageTitle: "Last page",
showTotal: true,
paginationTotalRenderer: customTotal,
sizePerPageList: [
{
text: "5",
value: 5,
},
{
text: "10",
value: 10,
},
{
text: "All",
value: profiles.length,
},
],
};
return (
<BootstrapTable
keyField="id"
hover
data={profiles}
columns={columnsProfile}
defaultSorted={defaultSorted}
filter={filterFactory()}
selectRow={selectRowClient}
noDataIndication="No record(s) found."
pagination={paginationFactory(options)}
/>
)
As you want material icon, I suggest to use material ui table. Please below example to edit or delete row from material ui table.
import React from 'react';
import MaterialTable from 'material-table';
export default function MaterialTableDemo() {
const [state, setState] = React.useState({
columns: [
{ title: 'Name', field: 'name' },
{ title: 'Surname', field: 'surname' },
{ title: 'Birth Year', field: 'birthYear', type: 'numeric' },
{
title: 'Birth Place',
field: 'birthCity',
lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
},
],
data: [
{ name: 'Mehmet', surname: 'Baran', birthYear: 1987, birthCity: 63 },
{
name: 'Zerya Betül',
surname: 'Baran',
birthYear: 2017,
birthCity: 34,
},
],
});
return (
<MaterialTable
title="Editable Example"
columns={state.columns}
data={state.data}
editable={{
onRowAdd: (newData) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
setState((prevState) => {
const data = [...prevState.data];
data.push(newData);
return { ...prevState, data };
});
}, 600);
}),
onRowUpdate: (newData, oldData) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
if (oldData) {
setState((prevState) => {
const data = [...prevState.data];
data[data.indexOf(oldData)] = newData;
return { ...prevState, data };
});
}
}, 600);
}),
onRowDelete: (oldData) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
setState((prevState) => {
const data = [...prevState.data];
data.splice(data.indexOf(oldData), 1);
return { ...prevState, data };
});
}, 600);
}),
}}
/>
);
}
I'm new on ReactJS and this is my first page that I created, but I'm having some problems with set variables.
What I need is fill the variable table.data with the values that comes from const response = await api.get('/users') and render the table with this values when page loads.
I have the following code:
import React, { useState, useEffect } from 'react';
import { Fade } from "#material-ui/core";
import MaterialTable from 'material-table';
import { makeStyles } from '#material-ui/core/styles';
import api from '../../services/api.js';
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
width: '70%',
margin: 'auto',
marginTop: 20,
boxShadow: '0px 0px 8px 0px rgba(0,0,0,0.4)'
}
}));
function User(props) {
const classes = useStyles();
const [checked, setChecked] = useState(false);
let table = {
data: [
{ name: "Patrick Mahomes", sector: "Quaterback", email: "patrick#nfl.com", tel: "1234" },
{ name: "Tom Brady", sector: "Quaterback", email: "tom#nfl.com", tel: "5678" },
{ name: "Julio Jones", sector: "Wide Receiver", email: "julio#nfl.com", tel: "9876" }
]
}
let config = {
columns: [
{ title: 'Name', field: 'name' },
{ title: 'Sector', field: 'sector' },
{ title: 'E-mail', field: 'email'},
{ title: 'Tel', field: 'tel'}
],
actions: [
{ icon: 'create', tooltip: 'Edit', onClick: (rowData) => alert('Edit')},
{ icon: 'lock', tooltip: 'Block', onClick: (rowData) => alert('Block')},
{ icon: 'delete', tooltip: 'Delete', onClick: (rowData) => alert('Delete')},
{ icon: 'visibility', tooltip: 'Access', onClick: (rowData) => alert('Access')},
{ icon: "add_box", tooltip: "Add", position: "toolbar", onClick: () => { alert('Add') } }
],
options: {
headerStyle: { color: 'rgba(0, 0, 0, 0.54)' },
actionsColumnIndex: -1,
exportButton: true,
paging: true,
pageSize: 10,
pageSizeOptions: [],
paginationType: 'normal'
},
localization: {
body: {
emptyDataSourceMessage: 'No data'
},
toolbar: {
searchTooltip: 'Search',
searchPlaceholder: 'Search',
exportTitle: 'Export'
},
pagination: {
labelRowsSelect: 'Lines',
labelDisplayedRows: '{from} to {to} for {count} itens',
firstTooltip: 'First',
previousTooltip: 'Previous',
nextTooltip: 'Next',
lastTooltip: 'Last'
},
header: {
actions: 'Actions'
}
}
}
useEffect(() => {
setChecked(prev => !prev);
async function loadUsers() {
const response = await api.get('/users');
table.data = response.data;
}
loadUsers();
}, [])
return (
<>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<Fade in={checked} style={{ transitionDelay: checked ? '300ms' : '0ms' }}>
<div className={classes.root}>
<MaterialTable editable={config.editable} options={config.options} localization={config.localization} title="Usuários" columns={config.columns} data={table.data} actions={config.actions}></MaterialTable>
</div>
</Fade>
</>
);
}
export default User;
The previous example will show 3 users that I fixed on variable table.data with 4 columns (name, sector, email, tel).
In a functional component, each render is really a new function call. So any variables you declare inside the component and destroyed and re-created. This means that table is set back to your initial value each render. Even if your useEffect is setting it correctly after the first render, it will just be reset on the next.
This is what state is for: to keep track of variables between renders. Replace your let table, with a new state hook.
const [table, setTable] = useState({
data: [
{ name: "Patrick Mahomes", sector: "Quaterback", email: "patrick#nfl.com", tel: "1234" },
{ name: "Tom Brady", sector: "Quaterback", email: "tom#nfl.com", tel: "5678" },
{ name: "Julio Jones", sector: "Wide Receiver", email: "julio#nfl.com", tel: "9876" }
]
});
Then use it like this:
useEffect(() => {
setChecked(prev => !prev);
async function loadUsers() {
const response = await api.get('/users');
setTable(prev => ({...prev, data: response.data});
}
loadUsers();
}, [])
Since table.data is not a state variable, it is regenerated as it was declared originally every time the component renders, meaning that by the time it arrives as a prop to your component it will always be the same value (when you change the value of table.data in useEffect it is too late). You need to change table.data to a state variable, and then in your useEffect hook you can update the value of table.data to the value of response.data. This will cause the component to be re-rendered but with the updated value.
Here's an example of how you might do that:
import React, { useState, useEffect } from 'react';
import { Fade } from "#material-ui/core";
import MaterialTable from 'material-table';
import { makeStyles } from '#material-ui/core/styles';
import api from '../../services/api.js';
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
width: '70%',
margin: 'auto',
marginTop: 20,
boxShadow: '0px 0px 8px 0px rgba(0,0,0,0.4)'
}
}));
function User(props) {
const classes = useStyles();
const [checked, setChecked] = useState(false);
const [tableData, setTableData] = useState([]);
let config = {
columns: [
{ title: 'Name', field: 'name' },
{ title: 'Sector', field: 'sector' },
{ title: 'E-mail', field: 'email'},
{ title: 'Tel', field: 'tel'}
],
actions: [
{ icon: 'create', tooltip: 'Edit', onClick: (rowData) => alert('Edit')},
{ icon: 'lock', tooltip: 'Block', onClick: (rowData) => alert('Block')},
{ icon: 'delete', tooltip: 'Delete', onClick: (rowData) => alert('Delete')},
{ icon: 'visibility', tooltip: 'Access', onClick: (rowData) => alert('Access')},
{ icon: "add_box", tooltip: "Add", position: "toolbar", onClick: () => { alert('Add') } }
],
options: {
headerStyle: { color: 'rgba(0, 0, 0, 0.54)' },
actionsColumnIndex: -1,
exportButton: true,
paging: true,
pageSize: 10,
pageSizeOptions: [],
paginationType: 'normal'
},
localization: {
body: {
emptyDataSourceMessage: 'No data'
},
toolbar: {
searchTooltip: 'Search',
searchPlaceholder: 'Search',
exportTitle: 'Export'
},
pagination: {
labelRowsSelect: 'Lines',
labelDisplayedRows: '{from} to {to} for {count} itens',
firstTooltip: 'First',
previousTooltip: 'Previous',
nextTooltip: 'Next',
lastTooltip: 'Last'
},
header: {
actions: 'Actions'
}
}
}
useEffect(() => {
setChecked(prev => !prev);
async function loadUsers() {
const response = await api.get('/users');
setTableData(response.data);
}
loadUsers();
}, [])
return (
<>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<Fade in={checked} style={{ transitionDelay: checked ? '300ms' : '0ms' }}>
<div className={classes.root}>
<MaterialTable editable={config.editable} options={config.options} localization={config.localization} title="Usuários" columns={config.columns} data={tableData} actions={config.actions}></MaterialTable>
</div>
</Fade>
</>
);
}
export default User;
I'm trying to add a button to a cell in a react bootstrap table with the following is my code:
import React, { Component } from "react";
import BootstrapTable from "react-bootstrap-table-next";
import { Button } from 'reactstrap';
class ActionsCard extends Component {
constructor(props) {
super(props);
this.state = {
actions: [{action: "Upgrade device", details: "Upgrade device to version 0.1.1", _id: "1"}],
valid: true
};
this.columns = [
{
text: "Action",
dataField: "action",
sort: true,
editable: false,
headerStyle: (colum, colIndex) => {
return { width: "5%", textAlign: "left" };
}
},
{
text: "Details",
dataField: "details",
sort: true,
editable: false,
headerStyle: (colum, colIndex) => {
return { width: "12%", textAlign: "left" };
}
},
{
sort: true,
headerStyle: (colum, colIndex) => {
return { width: "16%", textAlign: "left" };
},
Header: 'Test',
Cell: cell => (
<Button onClick={() => console.log(cell.original)}>Upgrade</Button>
),
}
];
}
render() {
return (
<React.Fragment>
<BootstrapTable
keyField="_id"
data={this.state.actions}
columns={this.columns}
noDataIndication="No Interfaces available"
defaultSorted={[{ dataField: "action", order: "asc" }]}
/>
</React.Fragment>
);
}
}
export default ActionsCard;
However, when I run the code, the two first columns of the table appear as expected, but the third column is simply empty.
You can use formatter to add button as in this discussion mention
{
dataField: "databasePkey",
text: "Remove",
formatter: (cellContent: string, row: IMyColumnDefinition) => {
if (row.canRemove)
return <button className="btn btn-danger btn-xs" onClick={() => this.handleDelete(row.databasePkey)}>Delete</button>
return null
},
},