ANT design 4 table input filed validate - antd

Im adding my react project for ant design4 table and ant design input fields. any one know to how can validate that input required
Thanks
stackablitz here
code here
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: text => <a>{text}</a>,
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
{
title: 'Tags',
key: 'tags',
dataIndex: 'tags',
render: tags => (
<>
{tags.map(tag => {
let color = tag.length > 5 ? 'geekblue' : 'green';
if (tag === 'loser') {
color = 'volcano';
}
return (
<Tag color={color} key={tag}>
{tag.toUpperCase()}
</Tag>
);
})}
</>
),
},
{
title: 'Action',
key: 'action',
render: (text, record) => (
<Space size="middle">
<a>Invite {record.name}</a>
<a>Delete</a>
</Space>
),
},
];
const data = [
{
key: '1',
name: 'John Brown',
age: <input/>,
address: 'New York No. 1 Lake Park',
tags: ['nice', 'developer'],
},
{
key: '2',
name: 'Jim Green',
age: <input/>,
address: 'London No. 1 Lake Park',
tags: ['loser'],
},
{
key: '3',
name: 'Joe Black',
age: <input/>,
address: 'Sidney No. 1 Lake Park',
tags: ['cool', 'teacher'],
},
];
const onFinish = values => {
console.log(values);
};
ReactDOM.render(
<div>
<Form name="control-hooks" onFinish={onFinish}>
<Table columns={columns} dataSource={data} /> <div><Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button> </Form.Item>

Just enclose the <input/> in <Form.Item> and use the rules prop of it. You can see all the possible rules here. I suggest use the <Input/> of antd and set a width on it.
const data = [
{
key: "1",
name: "John Brown",
age: (
<Form.Item
name="age1"
rules={[{ required: true, message: "Age is required" }]}
>
<Input style={{ width: 150 }} />
</Form.Item>
),
address: "New York No. 1 Lake Park",
tags: ["nice", "developer"],
},
...
];
see this working link

Related

Consumption of an api data into ant-design table react-typescript

interface DataType {
id: string;
first_name: string;
last_name: string;
email: string;
phone: string;
ip_address: string;
is_active: Boolean;
Avatar: string;
}
const columns: ColumnsType<DataType> = [
{
title: 'First Name',
dataIndex: 'first_name',
key: 'first_name',
render: (first_name, data) => {
return (
<div>
<img className='customers-avatar' src={data.Avatar} alt="" />
{first_name}
</div>
)
},
},
{
title: 'Last Name',
dataIndex: 'last_name',
key: 'last_name',
},
{
title: 'Email Address',
dataIndex: 'email',
key: 'email',
},
{
title: 'Phone Number',
dataIndex: 'phone',
key: 'phone',
},
{
title: 'Last Login',
render: () => {
return (
<p>April 2, 2022</p>
)
},
},
{
title: '',
key: 'action',
render: () => (
<Space size="middle">
<Link to="/shipments" className='space-action' >Shipment</Link>
<Link to="/" className='space-action-green'>Edit</Link>
</Space>
),
},
];
const Customers: React.FC = () => {
const [customersData, setCustomersData] = useState(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
getCustomers();
});
const getCustomers = () => {
setLoading(true);
return makeAPICall({
path: `get_customers`,
method: "GET",
})
.then((data) => {
setCustomersData(data);
setLoading(false);
console.log(data);
})
.catch((err) => {
setLoading(false);
console.log(err);
});
}
return (
<SiderLayout>
<div className="site-layout-background" style={{ padding: "40px 40px", minHeight: 710 }}>
<button type='submit'>Add Customer {" "} +</button>
{loading ? 'loading...' : (
<div>
{!customersData ? ("No data") : (<Table columns={columns} dataSource={customersData} />)}
</div>
)}
</div>
</SiderLayout>
)
}
export default Customers;
I've consumed the get_customers api, which I think I did it correctly, but the data is not displaying on the browser.
When I went to inspect element, I thought is as a result of CORS, so I turned on CORS, but it wasn't still working, it would fetch all the data in that process of loading the state, it would display a blank screen at the end.

nested dataIndex in Table of Ant Design

this is my code below
const columns = [
{
key: '1',
title: 'id',
dataIndex: 'id'
},
{
key: '2',
title: 'status',
dataIndex: 'status',
render: (text) => <a> {text} </a>
},
];
I wanna display data ( text/id ) like below code
const columns = [
{
key: '1',
title: 'id',
dataIndex: 'id'
},
{
key: '2',
title: 'status',
dataIndex: ['status', 'id'],
render: (text) => <a> {text} / {id} </a>
},
];
I tried to like this samples
1. dataIndex: ['status', 'id']
2. dataIndex: 'status.id'
but that doesn`t work. (version 4.14.0)
how can I display like that? please reply here. thanks.
I'll answer assuming what you pass to the dataSource is an array of objects which looks like below.
interface DataModel {
id: number;
status: string;
}
If so, you can use the second parameter in the render method which will have the record. Hence record.id will give you the id.
const columns = [
{
key: '1',
title: 'id',
dataIndex: 'id'
},
{
key: '2',
title: 'status',
dataIndex: ['status'],
render: (text: any, record: any) => <a> {text} / {record.id} </a>
},
];
try this solution
{
title: 'Name',
dataIndex: 'address',
key: 'name',
render: ({ city, street }) => (
<Typography>{`${city} ${street}`}</Typography>
),
},
try this
{
title: "Task",
dataIndex: ["task","name"]
},

Ant deisgn 4 table summary issue in the Table.Summary.Cell

Im usiing My react typescript project for Ant design 4 table . so when i adding ant design Summary table, got a following error
TS2741: Property 'index' is missing in type '{ children: Element; colSpan: number; }' but required in type 'SummaryCellProps'.
any one know how to fix that issue.
Thanks
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Table, Typography } from 'antd';
const { Text } = Typography;
const columns = [
{
title: 'Name',
dataIndex: 'name',
},
{
title: 'Borrow',
dataIndex: 'borrow',
},
{
title: 'Repayment',
dataIndex: 'repayment',
},
];
const data = [
{
key: '1',
name: 'John Brown',
borrow: 10,
repayment: 33,
},
{
key: '2',
name: 'Jim Green',
borrow: 100,
repayment: 0,
},
{
key: '3',
name: 'Joe Black',
borrow: 10,
repayment: 10,
},
{
key: '4',
name: 'Jim Red',
borrow: 75,
repayment: 45,
},
];
const fixedColumns = [
{
title: 'Name',
dataIndex: 'name',
fixed: true,
width: 100,
},
{
title: 'Description',
dataIndex: 'description',
},
];
const fixedData = [];
for (let i = 0; i < 6; i += 1) {
fixedData.push({
key: i,
name: i % 2 ? 'Light' : 'Bamboo',
description: 'Everything that has a beginning, has an end.',
});
}
ReactDOM.render(
<>
<Table
columns={columns}
dataSource={data}
pagination={false}
bordered
summary={pageData => {
let totalBorrow = 0;
let totalRepayment = 0;
pageData.forEach(({ borrow, repayment }) => {
totalBorrow += borrow;
totalRepayment += repayment;
});
return (
<>
<Table.Summary.Row>
<Table.Summary.Cell>Total</Table.Summary.Cell>
<Table.Summary.Cell>
<Text type="danger">{totalBorrow}</Text>
</Table.Summary.Cell>
<Table.Summary.Cell>
<Text>{totalRepayment}</Text>
</Table.Summary.Cell>
</Table.Summary.Row>
<Table.Summary.Row>
<Table.Summary.Cell>Balance</Table.Summary.Cell>
<Table.Summary.Cell colSpan={2}>
<Text type="danger">{totalBorrow - totalRepayment}</Text>
</Table.Summary.Cell>
</Table.Summary.Row>
</>
);
}}
/>
</>,
document.getElementById('container'),
);
Had this issue yesterday as well, looking at the SummeryCellProps the rc-table team made index required. So I just added <Table.Summary.Row index={1}> you need to iterate through your pagedata to add the index of the that column

Conflict on the React ant design table input total balance

Im tried to do some calculate part for my react ant design 4 table, i don't have idea for how to get when i entered value after get automatically calculate total and then submit. any onw know how to do that correctly.
Thanks
stack blitz here
This is my code part
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: text => <a>{text}</a>,
},
{
title: 'Book',
dataIndex: 'book',
key: 'book',
},
{
title: 'Pen',
dataIndex: 'pen',
key: 'pen',
},
{
title: 'Tools',
key: 'tools',
dataIndex: 'tools',
},
{
title: 'Total',
key: 'total',
dataIndex: 'total',
},
];
const data = [
{
key: '1',
name: 'John Brown',
book: <Form.Item name="book1" rules={[{required: true, message: " is required"}]}><Input style={{width: 150}}/></Form.Item>,
pen: <Form.Item name="oen1" rules={[{required: true, message: "is required"}]}><Input style={{width: 150}}/></Form.Item>,
tools: <Form.Item name="tools1" rules={[{required: true, message: " is required"}]}><Input style={{width: 150}}/></Form.Item>,
total:'00000'
},
];
const onFinish = values => {
console.log(values);
};
ReactDOM.render(
<div>
<Form name="control-hooks" onFinish={onFinish}>
<Table columns={columns} dataSource={data} />
<div>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</div>
</Form>
</div>, document.getElementById('container'));
I assumed the rows can be more than one. You can achieve this by:
You need a state. In react, in order to change something on the UI (e.g. total column) you need a state. Put your data array in state.
const [data, setData] = useState([ ... ])
You need to know which row the input was when you type in. You may add some distinction on input that is equal to row key. Here I suggest to put some number on the name of input:
<Form.Item name="book-1">...</Form.Item>
<Form.Item name="pen-1">...</Form.Item>
<Form.Item name="tools-1">...</Form.Item>
Use onValuesChange prop of the <Form> it triggers every time you type on the inputs and return the form values. With this, you can extract the number on input name and use that as a reference to know which row is about to change and perform setState.
I also suggest to use InputNumber instead of Input if you only need a number input.
Here is the working link. You can start/play around there if I did not hit what you want.
You may also look on antd table editable rows. This might be easiest to use than this

Is there a way to make api call when expanding table to show nested table?

In Ant Nested table - When expanding a row, I want to make an api call and get the data to show the nested table.
The function expandedRowRender, expects to return the nested table, it does not accept a promise.
How can I show a nested Ant table using ajax call?
I have tried to recreate the scenario for reference.
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Table } from "antd";
import reqwest from "reqwest";
const nestedColumns = [
{
title: "Name",
dataIndex: "name",
sorter: true,
render: name => `${name.first} ${name.last}`,
width: "20%"
},
{
title: "Gender",
dataIndex: "gender",
filters: [
{ text: "Male", value: "male" },
{ text: "Female", value: "female" }
],
width: "20%"
},
{
title: "Email",
dataIndex: "email"
}
];
class App extends React.Component {
state = {
data: []
};
fetch = (params = {}) => {
console.log("params:", params);
reqwest({
url: "https://randomuser.me/api",
method: "get",
data: {
results: 10,
...params
},
type: "json"
}).then(data => {
return (
<Table
columns={nestedColumns}
dataSource={data.results}
pagination={false}
/>
);
// this.setState({
// data: data.results
// });
});
};
expandedRowRender = () => {
this.fetch();
return <table columns={nestedColumns} dataSource={this.state.data} />;
};
render() {
const columns = [
{ title: "Name", dataIndex: "name", key: "name" },
{ title: "Platform", dataIndex: "platform", key: "platform" },
{ title: "Version", dataIndex: "version", key: "version" }
];
const data = [
{
key: 1,
name: "Screem",
platform: "iOS",
version: "10.3.4.5654"
}
];
return (
<Table
columns={columns}
dataSource={data}
pagination={false}
expandedRowRender={this.expandedRowRender}
/>
);
}
}
ReactDOM.render(<App />, document.getElementById("container"));
I try my level best to answer your question. Here is the reduced type of code and you can get an idea of how to do that.
In state,
state = {
data: null,
loading: false,
};
Here is your function to make API call,
fetch = (expanded, record) => {
axios.get(`put your api to load nested table`)
.then(res => {
const data = res.data;
this.setState({
...this.state.data,
data,
loading: true
})
}).catch(error => {
console.log(error, "error")
})
}
After that,
expandedRowRender=() => {
if(this.state.loading){
const nestedTableData = this.state.data.map(row => ({
key: row.id,
Id: row.id,
name: 'test',
gender: 'gender',
}))
const nestedColumns = [
{ title: "Name", dataIndex: "name", key: "name" },
{ title: "Gender", dataIndex: "gender", key: "gender" },
];
return <Table columns={nestedColumns} dataSource={nestedTableData } pagination={false} />
}
};
And put following code below return
<Table
className="components-table-demo-nested"
columns={columns}
dataSource={tableData}
expandable={{
expandedRowRender: this.expandedRowRender,
rowExpandable: record => true,
onExpand: this.fetch
}}
/>
I hope it may help you and let me know if it does. :)

Resources