make whole row clickable - javascript

i'm new on react(hooks) typescript, trying to learn by doing,
here i have created antd table(which works), on the right side of table is 'Edit' it is clickable and works well, but my question is how to make each row clickable instead of that 'Edit' ? like i could click anywhere on the row and it should take me to its 'Edit' link instead of me clicking just on 'Edit':
import { useTranslation } from "react-i18next";
const { t } = useTranslation();
const columns = [
{
title: t("tilaus.state"),
dataIndex: "state",
key: "state",
render: (value: OrderState) => (
<span className="material-icons">
</span>
),
},
{
title: t("request.parcelId"),
dataIndex: "parcelId",
key: "parcelId",
},
{
title: t("request.date"),
dataIndex: "date",
key: "date",
render: (value: Date) => <div>{value.toLocaleDateString("af-AF")}</div>,
},
{
title: t("request.sender"),
dataIndex: "sender",
key: "sender",
render: (value: CustomerDto) => <div>{value.name}</div>,
},
{
title: t("request.recipient"),
dataIndex: "recipient",
key: "recipient",
render: (value: CustomerDto) => <div>{value.name}</div>,
},
{
title: t("request.price"),
dataIndex: "price",
key: "price",
},
{
title: "",
dataIndex: "id",
key: "id",
render: (value: string) => (
<Link to={"details/" + value}>{t("request.edit")}</Link>
),
},
];
<Table
dataSource={orders}
columns={columns}
pagination={false}
scroll={{ x: true }}
onRow={(record, rowIndex) => {
return {
onClick: (event) => {
handleClick(record);
},
};
}}
/>

Looks like you are using ant.d table. I've grabbed one of the examples and console logged the output. You can find it here: https://codesandbox.io/s/s1xds?file=/index.js to show you how the onclick in the entire row is being triggered.
For your specific thing, you need to change onRow prop. You can't add a Link directly to the row, but you can use history from react-router (if you are using it, docs here) or directly mutate the URL when onclick is called.
So in your case, you'll have to do this:
<Table
dataSource={orders}
columns={columns}
pagination={false}
scroll={{ x: true }}
onRow={(record, rowIndex) => {
return {
onClick: (event) => {
history.push(`/details/${record.id}`);
},
};
}}
/>
or
<Table
dataSource={orders}
columns={columns}
pagination={false}
scroll={{ x: true }}
onRow={(record, rowIndex) => {
return {
onClick: (event) => {
window.location.href = `${window.location.href}/details/${record.id}`
},
};
}}
/>

Related

Insert Icon on AntD Column Table based on Data Device

I have a problem here please anyone can help me?
I have a trouble with Ant Design table here, in Source column here I want to insert Icon, I already have inserted an icon but I want the Icon change based on the data of the device, if device Id = 1 it would be "Human Icon" that will showed up, but if device id = 2 it would be "Computer Icon" that will show.
Here's the code :
import React, { useEffect, useState } from 'react';
import { Card, Col, Divider, Layout, Row, Table, Tag } from 'antd';
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Content, Footer, Header } from 'antd/lib/layout/layout';
import 'antd/dist/antd.css';
import '../Page/Dashboard.css';
import { LaptopOutlined, UserAddOutlined, UserOutlined } from '#ant-design/icons';
const columns = [
{
title: "No",
dataIndex: "id",
key: "id",
},
{
title: 'Device ID',
dataIndex: "dev_id",
key: "dev_id",
},
{
title: 'Message ID',
dataIndex: "msg_id",
key: "msg_id",
},
{
title: 'Time Stamp',
dataIndex: "time_stamp",
key: "time_stamp",
},
{
title: 'RFID',
dataIndex: "rfid",
key: "rfid",
},
{
title: 'Data Hewan',
dataIndex: "animals",
key: "animals",
},
{
title: 'Weight (kg)',
dataIndex: "weight",
key: "weight",
},
{
title: 'Temperature (Celcius)',
dataIndex: "temp",
key: "temp",
},
{
title: 'Tags',
dataIndex: "tags",
key: "tags",
render: (_, { tags }) => (
<>
{tags.map((tag) => {
let color = 'geekblue';
if (tag === 'Invalid Data') {
color = 'volcano';
} else {
color = 'geekblue';
}
return (
<Tag color={color} key={tag}>
{tag.toUpperCase()}
</Tag>
);
})}
</>
),
},
{
title: 'Source',
dataIndex: "",
key: "",
render: text => <UserOutlined />
}
];
export default function Dashboard(){
return (
<Table column={columns} dataSource={dataQurban} />
)}
Thank you I hope you'll could help me!
{
title: 'Source',
dataIndex: "",
key: "",
render: (_: any, record: any) => record.dev_id === 1 ? <UserOutlined /> : <ComputerIcon />
}
The code above is the direct solution.
You could aslo define a variable if you want to optimize the code.
const iconObj = {
1: <Icon1 />,
2: <Icon2 />,
3: <Icon3 />,
// ...
}
// ...
{
title: 'Source',
dataIndex: "",
key: "",
render: (_, record) => iconObj[record.dev_id]
}

cant show data in table using mobx state tree

I am getting the following error when trying to pass data to material ui table, the table isnt displayed and it crash. Cannot modify '', the object is protected and can only be modified by using an action.
im using typescript and mobx state tree
setTreasurers: flow(function* () {
return self.treasurerData = yield getAllTreasurers();
})
var showTreasurerData = userStore.getTreasurerData
const cloneSheeps = [...showTreasurerData];
return (
<div>
<MaterialTable
title="Tesoreros"
columns={[
{ title: "Email", field: "email" },
{ title: "Cuit", field: "cuit" },
{
title: "Verificado",
field: "verified",
},
]}
data={cloneSheeps}
options={{
sorting: true,
actionsColumnIndex: -1
}}
localization={
{ header: { actions: 'Acciones' } }
}
actions={
[
{
position: "auto",
icon: "done",
tooltip: "Enable User",
onClick: (event, user) => {
var isVerified = true;
ManageTreasurerVerification(user, isVerified)
},
},
{
icon: "cancel",
tooltip: "Disable User",
onClick: (event, user) => {
var isVerified = false;
ManageTreasurerVerification(user, isVerified)
},
},
]}
/>

Can not hide add-button like isEditHiden/isDeleteHiden in material table conditionally

In material-table there is option for hiding edit and delete button conditionally like
<MaterialTable
/// other props
editable={
10 > 5 && {
isEditHidden: () => !10 > 5, // This is condition
isDeleteHidden: () => !10 > 5, // This is condition
onRowAdd: newData =>
}),
onRowUpdate: (newData, oldData) =>
}),
onRowDelete: oldData =>
})
}
}
/>
if isEditHidden or isDeleteHidden is true those button hide. I want to hide add button (beside search icon) also. But i couldn't find any option. Is there any option?
You need to remove editable props and actions props for custom actions if needed and then can use hidden/disabled property to hide/disable action button.
import React from "react";
import MaterialTable from "material-table";
export default function DisableFieldEditable() {
const { useState } = React;
const [columns, setColumns] = useState([
{ title: "Name", field: "name", editable: "onUpdate" },
{ title: "Surname", field: "surname", editable: "never" },
{ title: "Birth Year", field: "birthYear", type: "numeric" },
{
title: "Birth Place",
field: "birthCity",
lookup: { 34: "İstanbul", 63: "Şanlıurfa" }
}
]);
const [data, setData] = useState([
{ name: "Mehmet", surname: "Baran", birthYear: 1987, birthCity: 63 },
{ name: "Zerya Betül", surname: "Baran", birthYear: 2017, birthCity: 34 }
]);
return (
<MaterialTable
title="Disable Field Editable Preview"
columns={columns}
data={data}
actions={[
{
icon: "add",
tooltip: "Add User",
hidden: 10 < 5,
isFreeAction: true,
onClick: (event, rowData) => {
// Perform add operation
}
},
{
icon: 'edit',
tooltip: 'Edit User',
hidden: true,
onClick: (event, rowData) => {
// Perform edit operation
}
},
{
icon: 'delete',
tooltip: 'Delete User',
disabled: true,
onClick: (event, rowData) => {
// Perform delete operation
}
}
]}
/>
);
}

Error using template slot and slot-scope on VueJS

Error using a slot and slot-scope on VueJS to put into a column of a table.
A template as follows:
<b-table hover striped :items="users" :fields="fields">
<template slot="actions" slot-scope="data">
<b-button variant="warning" #click="loadUser(data.item)" class="mr-2">
<i class="fa fa-pencil"></i>
</b-button>
<b-button variant="danger" #click="loadUser(data.item, 'remove')">
<i class="fa fa-trash"></i>
</b-button>
</template>
</b-table>
After all, I'm able to get users on DB. And have success to show it on table. But, the buttons on slot can't.
The idea is put two buttons:
The update button
The delete button
And each button manage one function.
<script>
import { baseApiUrl, showError } from '#/global'
import axios from 'axios'
export default {
name: 'UserAdmin',
data: function(){
return {
mode: 'save',
user: {},
users: [],
fields: [
{ key: 'id', label: 'Código', sortable: true},
{ key: 'name', label: 'Nome', sortable: true},
{ key: 'email', label: 'E-mail', sortable: true},
{ key: 'adminMaster', label: 'Administrador', sortable: true,
formatter: value => value ? 'Sim' : 'Não'},
{key: 'adminEnterprise', label: 'Chefe de Empreendimento', sortable: true,
formatter: value => value ? 'Sim' : 'Não'},
{ key: 'manager', label: 'Gerente', sortable: true,
formatter: value => value ? 'Sim' : 'Não'},
{ key: 'customer', label: 'Cliente', sortable: true,
formatter: value => value ? 'Sim' : 'Não'},
{ key: 'actions', label: 'Ações'}
],
}
},
methods: {
loadUsers() {
const url = `${baseApiUrl}/users`
axios.get(url).then(res => {
this.users = res.data
})
},
reset() {
this.mode = 'save'
this.user = {}
this.loadUsers()
},
save() {
const method = this.user.id ? 'put' : 'post'
const id = this.user.id ? `/${this.user.id}` : ''
axios[method](`${baseApiUrl}/users${id}`, this.user)
.then(() => {
this.$toasted.global.defaultSuccess()
this.reset()
})
.catch(showError)
},
remove() {
const id = this.user.id
axios.delete(`${baseApiUrl}/users/${id}`)
.then(() => {
this.$toasted.global.defaultSuccess()
this.reset()
})
.catch(showError)
},
loadUser(user, mode = 'save') {
this.mode = mode
this.user = { ...user }
}
},
mounted() {
this.loadUsers()
}
}
</script>
Alright, so, it looks like you're using an official release of BV 2.0., BV is preparing for Vue 3 which is revising the component-slotting system.
As such, BV has renamed the custom slots, you need to use cell({key}) like so:
<template slot="cell(actions)" slot-scope="data">

How to add a button inside a react bootstrap table?

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
},
},

Categories

Resources