How to add dynamic link to table data - reactjs

I'm working on a simple table using ReactJs and ant design, my problem is I don't know how to put value on the links using their data keys.
Thanks,
Codepen
SAMPLE CODE
const { Table } = antd;
const columns = [{
title: 'Name',
dataIndex: 'name',
render: text => {text},
}, {
title: 'Cash Assets',
className: 'column-money',
dataIndex: 'money',
}, {
title: 'Address',
dataIndex: 'address',
}];
const data = [{
key: '1',
name: 'John Brown',
money: '¥300,000.00',
address: 'New York No. 1 Lake Park',
}, {
key: '2',
name: 'Jim Green',
money: '¥1,256,000.00',
address: 'London No. 1 Lake Park',
}, {
key: '3',
name: 'Joe Black',
money: '¥120,000.00',
address: 'Sidney No. 1 Lake Park',
}];
ReactDOM.render(
<Table
columns={columns}
dataSource={data}
bordered
title={() => 'Header'}
footer={() => 'Footer'}
/>
, mountNode);

Change this
render: text => {text}
to this
render: (text, record) => <a href={'user/' + record.name}>{text}</a>
if you're using router
render: (text, record) => <Link to={'user/' + record.name}>{text}</Link>

As you can see, the column rendering logic is provided by the columns array of objects. So if you want to include any logic ( like giving values to URLs ), you have to alter the corresponding object's render key:
const columns = [{
title: 'Name',
dataIndex: 'name',
render: text => <a href={`http://<some-domain>.com/user/${text.split(' ').join()}`}>{text}</a>, // changed function, so that data maps to links. eg: http:??<some-domain>.com/user/JohnBrown
}, {
/* */
}, {
/* */
}];
Alternatively, you could create an object for looking up urls, like so:
const mapping = {
'John Brown': 'http://yourdomain.com/user/134123',
'Jin Green': 'http://yourdomain.com/user/897983',
/* more persons */
}
const columns = [{
title: 'Name',
dataIndex: 'name',
render: text => <a href={mapping[text]}>{text}</a>, // changed function
}, {
/* */
}, {
/* */
}];

Related

React with Ant desing Table.set column by useSate header have check box.Check box not working

I want to put a checkbox in the header column where the column uses useState. But the checkbox is not working.but checkBox have update is true
import React from 'react';
import 'antd/dist/antd.css';
import { Button, Checkbox, Form, Input,Space,Table } from "antd";
const App = () => {
const [checkBox,setCheckBox]=React.useState(false)
const [columns,setColumns] = React.useState([
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: ()=>{
return (
<>
<Space>
age
<Checkbox onChange={(e)=>setCheckBox(e.target.checked)}
checked={checkBox}
/>
</Space>
</>
)
},
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
}]);
const dataSource = [
{
key: '1',
name: 'Mike',
age: 32,
address: '10 Downing Street',
},
{
key: '2',
name: 'John',
age: 42,
address: '10 Downing Street',
}];
React.useEffect(()=>{
setColumns(columns.filter((ele)=>ele.dataIndex!=='name'))
},[])
return (
<>
<Table columns={columns} dataSource={dataSource} />
</>
)
}
export default App;
can not checked but in useState in update
enter image description here
you can coppy into this link:enter link description here
To solve this checkbox issue need to use state.
Here is the Sandbox Link with working code.
To implement checkbox at Antd table, you need to add property rowSelection at the table
<Table rowSelection={rowSelection} columns={columns} dataSource={dataSource} />
First addd selectedRowKeys state to keep the information of selected keys
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
Then create data & column data
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
];
const dataSource = [
{
key: '1',
name: 'Mike',
age: 32,
address: '10 Downing Street',
},
{
key: '2',
name: 'John',
age: 42,
address: '10 Downing Street',
}
];
Add row selection const as the input of Table's rowSelection property that contain onChange: (keys) => setSelectedRowKeys(keys), that will update the selectedRowKeys state on any checkbox change.
const rowSelection = {
selectedRowKeys,
onChange: (keys) => setSelectedRowKeys(keys),
selections: [
Table.SELECTION_ALL,
Table.SELECTION_INVERT,
Table.SELECTION_NONE,
]
};
And here is the complete code:
import { useCallback, useState, useEffect } from "react";
import { Table } from 'antd';
import './App.css';
export default function App() {
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
];
const dataSource = [
{
key: '1',
name: 'Mike',
age: 32,
address: '10 Downing Street',
},
{
key: '2',
name: 'John',
age: 42,
address: '10 Downing Street',
}
];
// this useEffect is used to watch selection changes and log the values
useEffect(() => {
console.log(selectedRowKeys)
}, [selectedRowKeys])
const rowSelection = {
selectedRowKeys,
onChange: (keys) => setSelectedRowKeys(keys),
selections: [
Table.SELECTION_ALL,
Table.SELECTION_INVERT,
Table.SELECTION_NONE,
]
};
return <Table rowSelection={rowSelection} columns={columns} dataSource={dataSource} />
}

Can't select checkbox table Ant Design

I'm currently learning ReactJs and using Ant Design as a UI library. I have some problems when I tried to use the Selection (Checkbox Table). At first, it's fine with some basic interaction, I can get the selectedRowKeys, the selectedRow data normally to interact with the database. But when I need the Table to check some rows according to the data, it got some problems. When I set the props selectedRowKeys with data, it selects the right checkbox I want but I can't uncheck or select another checkbox. It shows the error:
Uncaught TypeError: clone.push is not a function at arrAdd ...
Here's how I'm doing it:
import React, { useState } from 'react';
import { Table, Radio, Divider } from 'antd';
const columns = [
{
title: 'Name',
dataIndex: 'name',
render: (text) => <a>{text}</a>,
},
{
title: 'Age',
dataIndex: 'age',
},
{
title: 'Address',
dataIndex: 'address',
},
];
const data = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Jack',
age: 20,
address: 'Somewhere else',
},
]; // rowSelection object indicates the need for row selection
const rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
getCheckboxProps: (record) => ({
name: record.name,
}),
};
const Demo = () => {
const dataKeys = "1,2"; //after handling data from server, I got a string like this which I can pass to Table
return (
<div>
<Table
rowSelection={{
selectedRowKeys: dataKeys,
type: selectionType,
...rowSelection,
}}
columns={columns}
dataSource={data}
/>
</div>
);
};
ReactDOM.render(<Demo />, mountNode);

react app how can I set the state of the radio button in an antd table?

I try to understand antd.
I have here from the documentation Table Example 3.
When the radio button is clicked, this state is set and the row is selected.
If i clicked a cell of a row, the row should also be selected and the ckeck state of the radio button should be set.
Does anyone have any idea how to do that?
import React from 'react';
import { Table } from 'antd';
import 'antd/dist/antd.css';
const columns = [
{
title: 'Name',
dataIndex: 'name',
render: (text: string) => <a>{text}</a>,
},
{
title: 'Age',
dataIndex: 'age',
},
{
title: 'Address',
dataIndex: 'address',
},
];
interface DataType {
key: React.Key;
name: string;
age: number;
address: string;
}
const data: DataType[] = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sidney No. 1 Lake Park',
},
{
key: '4',
name: 'Disabled User',
age: 99,
address: 'Sidney No. 1 Lake Park',
},
];
// rowSelection object indicates the need for row selection
const rowSelection = {
onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
};
export default function TableDemo() {
return (
<React.Fragment>
<Table
rowSelection={{
type: 'radio',
...rowSelection,
}}
columns={columns}
dataSource={data}
/>
</React.Fragment>
);
}
Current v4 docs for table are pretty extensive. Buried in there is this.
"Rows can be selectable by making first column as a selectable column. You can use rowSelection.type to set selection type. Default is checkbox.
selection happens when clicking checkbox by default. You can see https://codesandbox.io/s/000vqw38rl if you need row-click selection behavior."
Seems like what you're looking for. Easy to miss, though.

Adding button inside Ant-design table column

I want to create a button inside table column. I have tried using Cell but its not working.
Cell: ({ cell }) => (
<button value={cell.row.values.name} onClick={props.handleClickGroup}>
{cell.row.values.name}
</button>
)
You can render a button inside column using the render property:
const columns = [
{
title: 'Button Test',
key: 'key',
dataIndex: 'key',
render: (text, record) => (
<button onClick={()=> console.log(record)}>
{"Button Text"}
</button>
),
},
];
const data = [
{
key: '1',
name: 'John Doe',
age: 35,
address: 'New York No. 1 Lake Park'
},
];
<Table
columns={columns}
dataSource={data}
/>
If it is ant-design for Vue you can try this:
Template
<template>
<a-table :columns="columns" :data-source="data">
<a-button slot="action">{ buttonText }</a-button>
</a-table>
</template>
Script
<script>
const columns = [
{ title: 'Name', dataIndex: 'name', key: 'name' },
{ title: 'Age', dataIndex: 'age', key: 'age' },
{ title: 'Address', dataIndex: 'address', key: 'address' },
{ title: 'Action', dataIndex: '', key: 'x', scopedSlots: { customRender: 'action' } },
]
const data = [
{
key: 1,
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
description: 'My name is John Brown, I am 32 years old, living in New York No. 1 Lake Park.',
},
{
key: 2,
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
description: 'My name is Jim Green, I am 42 years old, living in London No. 1 Lake Park.',
},
]
export default{
data(){
return{
data,
columns,
buttonText: "view"
}
}
}
</script>
You can find more information on their site https://antdv.com/components/table/ under Expandable Row

Ant design sort table code not working on the react typescript

I used following ant design sort table code in react type script, its not working correctly anyone know how to do that correctly
My code here
import { Table } from 'antd';
import * as React from 'react';
import { Table } from 'antd';
const columns = [
{
title: 'Name',
dataIndex: 'name',
filters: [
{
text: 'Joe',
value: 'Joe',
},
{
text: 'Jim',
value: 'Jim',
},
{
text: 'Submenu',
value: 'Submenu',
children: [
{
text: 'Green',
value: 'Green',
},
{
text: 'Black',
value: 'Black',
},
],
},
],
// specify the condition of filtering result
// here is that finding the name started with `value`
onFilter: (value:any, record:any) => record.name.indexOf(value) === 0,
sorter: (a:any, b:any) => a.name.length - b.name.length,
sortDirections: ['descend'],
},
{
title: 'Age',
dataIndex: 'age',
defaultSortOrder: 'descend',
sorter: (a:any, b:any) => a.age - b.age,
},
{
title: 'Address',
dataIndex: 'address',
filters: [
{
text: 'London',
value: 'London',
},
{
text: 'New York',
value: 'New York',
},
],
filterMultiple: false,
onFilter: (value:any, record:any) => record.address.indexOf(value) === 0,
sorter: (a:any, b:any) => a.address.length - b.address.length,
sortDirections: ['descend', 'ascend'],
},
];
const data = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sidney No. 1 Lake Park',
},
{
key: '4',
name: 'Jim Red',
age: 32,
address: 'London No. 2 Lake Park',
},
];
function onChange(pagination:any, filters:any, sorter:any, extra:any) {
console.log('params', pagination, filters, sorter, extra);
}
//Table sample data
export class Customertable extends React.Component {
render() {
return (
/* Start Search button*/
<div className="customertable-section">
<div>
<Table columns={columns} dataSource={data} onChange={onChange} />
</div>
</div>
/* End of Search button*/
);
}
}
While declaring the variable in typescript, you need to give it like, columns: any = [] and data: any = []..
And while making table , you should give the props like,
<Table columns={this.columns} dataSource={this.data} />
Working sample antd table with typescript here...
To add on to Maniraj's comment, the documentation provides a section for Typescript specific usage:
https://ant.design/components/table/#Using-in-TypeScript
Setting the type of columns is possible by importing ColumnsType from 'antd/es/table'
Here the solution that may help someone. You should write type for your table config using default ant types and then in compare func, your item is DefaultRecordType, func returns number.
const TABLE_COLUMNS: ColumnsType<DefaultRecordType> = [
{
title: 'ISO #',
dataIndex: 'iso',
key: 'iso',
sorter: (a: DefaultRecordType, b: DefaultRecordType): number =>
a.iso.localeCompare(b.iso),
},]
You can simply sort your ant design table's column by replace your old code with new:
Old Code:
sorter: (a:any, b:any) => a.name.length - b.name.length,
New Code:
sorter: (a:any, b:any) => a.name.localeCompare(b.name),

Resources