I'm generating a sortable table in reactjs using mdbreact like so
import React from 'react';
import { MDBDataTable } from 'mdbreact';
const tableData = {
columns: [
{
field: 'first_name',
label: 'First Name'
},
{
field: 'last_name',
label: 'Last Name'
},
{
field: 'age',
label: 'Age'
}
],
rows: [
{
first_name: 'John',
last_name: 'Smith',
age: 29
},
{
first_name: 'Jane',
last_name: 'Doe',
age: 37
}
]
class Table extends React.Component {
render() {
return(
<MDBDataTable data={tableData} />
)
}
}
export default Table;
(the above is a simplification of the table i'm working with)
At the moment i'm using something similar to the below to target the first 5 th elements in css:
th:nth-of-type(-n+5) {
text-align: left;
}
But is there a way to either apply a class of some sort by column or cell or apply styling on the js level?
Specifically i would like to apply a class to the age th and td elements, wherever they may lie in the column order
Related
I need a checkbox in all columns of a row in the Ant Design table. i.e in the given sandbox, the table should have 3 checkboxes instead of John Brown, 32 & New York No. 1 Lake Park. Please help me out.
Thank you.
Reference: https://codesandbox.io/s/flamboyant-bogdan-qwhes
Here is working example in sandbox.
You are able to render whatever you want in column cell using render prop of column in Ant. So if you are able to put there function that render checkbox component.
If you want to control checkboxes, you need to set checked and onChange props according checkbox API. Here I used factory pattern to use one function to handle at each checkbox.
Please check the code below:
You are not adding any functionality for selectedRowKeys, rowSelection.
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Table } from 'antd';
const columns = [{
title: 'Name',
dataIndex: 'name',
render: text => {text},
}, {
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: 'Joe Black',
age: 32,
address: 'Sidney No. 1 Lake Park',
}, {
key: '4',
name: 'Disabled User',
age: 99,
address: 'Sidney No. 1 Lake Park',
}];
class App extends React.Component {
state = {
selectedRowKeys: [],
};
selectRow = (record) => {
const selectedRowKeys = [...this.state.selectedRowKeys];
if (selectedRowKeys.indexOf(record.key) >= 0) {
selectedRowKeys.splice(selectedRowKeys.indexOf(record.key), 1);
} else {
selectedRowKeys.push(record.key);
}
this.setState({ selectedRowKeys });
}
onSelectedRowKeysChange = (selectedRowKeys) => {
this.setState({ selectedRowKeys });
}
render() {
const { selectedRowKeys } = this.state;
const rowSelection = {
selectedRowKeys,
onChange: this.onSelectedRowKeysChange,
};
return (
<Table
rowSelection={rowSelection}
columns={columns}
dataSource={data}
onRow={(record) => ({
onClick: () => {
this.selectRow(record);
},
})}
/>
);
}
}
ReactDOM.render(<App />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/antd/4.4.3/antd.min.js"></script>
I'm not use React Hook in TypeScript but I have a few lines of code like below:
const [columns] = React.useState<Column[]>([
{ name: 'product', title: 'Product' },
{ name: 'region', title: 'Region' },
{ name: 'amount', title: 'Sale Amount' },
{ name: 'saleDate', title: 'Sale Date' },
{ name: 'customer', title: 'Customer' },
]);
const [rows] = React.useState<ISale[]>(sales);
const [pageSizes] = React.useState<number[]>([5, 10, 15]);
const [currencyColumns] = React.useState<string[]>(['amount']);
I want to use these React Hook in Class but I don't know how to convert them!
Can someone help me? Thanks!
This is how you use class based components when you are working with TypeScript and React.
First, you need to define an interface or type alias for your class component's state/props.
interface YourComponentState {
columns: Column[];
rows: ISale[];
pageSizes: number[];
currencyColumns: string[];
}
Then, you will need to supply the generic type parameters for React.Component with the types for the props/state.
class YourComponentName extends React.Component<{}, YourComponentState> {
constructor(props) {
super(props);
this.state = {
columns: [
{ name: 'product', title: 'Product' },
{ name: 'region', title: 'Region' },
{ name: 'amount', title: 'Sale Amount' },
{ name: 'saleDate', title: 'Sale Date' },
{ name: 'customer', title: 'Customer' },
],
rows: sales,
pageSizes: [5, 10, 15],
currencyColumns: ['amount'],
}
}
}
In class based react components, you cannot use hooks.
so, if you want something to store in state of class based component. you are going to:
class YourComponentName extends React.Component {
constructor(props) {
super(props);
this.state = {
columns: [
{ name: 'product', title: 'Product' },
{ name: 'region', title: 'Region' },
{ name: 'amount', title: 'Sale Amount' },
{ name: 'saleDate', title: 'Sale Date' },
{ name: 'customer', title: 'Customer' },
],
rows: sales,
pageSizes: [5, 10, 15],
currencyColumns: ['amount']
}
}
}
you can access them in your component:
this.state.columns
So, I have a API which returns the data which should be shown in table with datatable option.
I'm using 'mdbreact' to use datatable.
But there is no documentation about pushing array variables into rows of datatables. How to push my array variables into rows of datatables ?
My code :
import React, { Component } from 'react';
import { MDBDataTable } from 'mdbreact';
class DummyTest extends Component {
DummyFunc() {
var data = {
columns: [
{
label: 'Location',
field: 'Location',
sort: 'asc',
width: 150
},
{
label: 'Entry Time',
field: 'EntryTime',
sort: 'asc',
width: 150
},
{
label: 'Exit Time',
field: 'ExitTime',
sort: 'asc',
width: 150
},
],
rows: [
]
};
const datatableProps = {data, rows: datas};
}
In return
<MDBDataTable
striped
bordered
hover
data={datatableProps}
/>
you can update the rows data after fetching it from the API. sample using hooks.
something like this.setState({datatableProps: ...datatableProps, rows: API_ROWD_ATA})
I'm implementing ReactTable, the first example from its documentation, but each cell from the table goes to a new line:
ReactTable
This is my react table component:
import React, {PureComponent} from 'react';
import ReactTable from 'react-table';
export default class ExampleTable extends PureComponent {
render() {
const data = [{
name: 'Tanner Linsley',
age: 26,
friend: {
name: 'Jason Maurer',
age: 23,
}
},{
name: 'Bla bla',
age: 29,
friend: {
name: 'RAra Ra',
age: 98,
}
}]
const columns = [{
Header: 'Name',
accessor: 'name' // String-based value accessors!
}, {
Header: 'Age',
accessor: 'age',
Cell: props => <span className='number'>{props.value}</span> // Custom cell components!
}, {
id: 'friendName', // Required because our accessor is not a string
Header: 'Friend Name',
accessor: d => d.friend.name // Custom value accessors!
}, {
Header: props => <span>Friend Age</span>, // Custom header components!
accessor: 'friend.age'
}]
return <ReactTable
data={data}
columns={columns}
/>
}
}
And this is how I import the component:
import ExampleTable from './tables/example';
class TableView extends Component {
getExample() {
return (
<ExampleTable/>
)
}
render() {
return (
<div>
{this.getExample()}
</div>
);
}
}
Any idea why each cell is going to a new line?
Probably is something stupid I'm just starting with React.
Thanks in advance.
Found it!
It was something stupid, I wasn't importing the ReactTable css:
import "react-table/react-table.css";
I have integrated datatable in my react js web app.
It works with sample data as i have mentioned in the code pagelist
I have tried to make it component but did not get the result. I am new
in react and did not able to clue to further progress.
Here the list of my import packages
import axios from 'axios'
import React, {Component} from 'react'
import {BrowserRouter,Route,Switch,Link} from 'react-router-dom'
import { MDBDataTable} from 'mdbreact';
// The below call get the data as i have confirmed in the console log
axios.get('/api/pagelist').then(response => {
var pagelist = JSON.stringify(response.data);
console.log(pagelist);
});
//Sample test data which works with the example
var pagelist = [{
name: 'Tiger Nixon',
position: 'System Architect',
office: 'Edinburgh',
age: '61',
date: '2011/04/25',
salary: '$12320'
},
{
name: 'Gavin Joyce',
position: 'Developer',
office: 'Edinburgh',
age: '42',
date: '2010/12/22',
salary: '$92'
},
{
name: 'Jennifer Chang',
position: 'Regional Director',
office: 'Singapore',
age: '28',
date: '2010/11/14',
salary: '$357'
},
{
name: 'Donna Snider',
position: 'Customer Support',
office: 'New York',
age: '27',
date: '2011/01/25',
salary: '$112'
}
];
// Just copy the function and change columns as guided by the documentation
const DatatablePage = () => {
const data = {
columns: [{
label: 'ID',
field: 'id',
sort: 'asc',
width: 60
},
{
label: 'Name',
field: 'name',
sort: 'asc',
width: 150
},
{
label: 'Title',
field: 'title',
sort: 'asc',
width: 150
},
{
label: 'Slug',
field: 'slug',
sort: 'asc',
width: 100
},
{
label: 'Content',
field: 'content',
sort: 'asc',
width: 250
},
{
label: 'Created',
field: 'created_at',
sort: 'asc',
width: 100
}
],
rows: pagelist
};
return (
<MDBDataTable striped bordered hover data = {data}/>
);
}
//Finally exported it
export default DatatablePage;
Looks like a scoping issue to me. The data variable you're storing the page data in is scoped to the axios callback. Once the code leaves that callback, your data is no longer accessible.
axios.get('/api/pagelist').then(response => {
// pageList scoped locally. not accessible outside. this is why the
// console.log works, but there's no data in the table.
var pagelist = JSON.stringify(response.data);
console.log(pagelist);
});
Assuming you're using a component, I suggest adding a constructor and that you create a state property. E.g.
constructor(props) {
super(props);
this.state = {pageList: []} ;
}
You need to then update this in the axios.get....
axios.get('/api/pagelist').then(response => {
// The below line may not be exactly correct. May need to review.
this.setState({pagelist: JSON.stringify(response.data)}, console.log("state updated));
});
Finally, the rows assignment in the datatables method needs to be
rows: this.state.pagelist