I work on a React app and there is a component using DataTable (reference is here).
The default font-size looks too small so I want to change to make it look bigger.
I try to set the style to the table as the code below but it doesn't work.
Here is my code:
import React from 'react';
import ReactDOM from 'react-dom';
import DataTable from 'react-data-table-component';
export default class MyTable2 extends React.Component {
constructor(props) {
super(props);
const data = [];
for (var i = 0; i < 200; i++) {
data.push({ id: i, title: 'Conan the Barbarian' + i, summary: 'Orphaned boy Conan is enslaved after his village is destroyed...', year: '1982', expanderDisabled: true, image: 'http://conan.image.png' })
}
this.state = {
rs: data
}
}
render() {
const columns = [
{
name: 'Title',
selector: 'title',
sortable: true,
},
{
name: 'Year',
selector: 'year',
sortable: true
},
];
const handleChange = (state) => {
console.log('Selected Rows: ', state.selectedRows);
};
let styleobj = { "font-size": "25px" } //try to set the font-size here
return (
<DataTable
className="dataTables_wrapper"
title="Arnold Movies"
columns={columns}
data={this.state.rs}
selectableRows // add for checkbox selection
onTableUpdate={handleChange}
pagination
style={styleobj}
/>
)
}
}
Is there anyone here can suggest me a solution?
Thank you in advanced.
Can you try this
// Override the row font size
const myNewTheme= {
rows: {
fontSize: '25px'
}
}
<DataTable
className="dataTables_wrapper"
title="Arnold Movies"
columns={columns}
data={this.state.rs}
selectableRows // add for checkbox selection
onTableUpdate={handleChange}
pagination
customTheme={myNewTheme}
/>
Theme reference
Source file
If you want to change an individual cell font size, you can do this
const columns = [
{
name: 'Title',
selector: 'title',
sortable: true,
cell: row => <div style={{fontSize: 25}}>{row.title}</div>
}]
Hi #humanbean answer is correct, you can fix the inline stile or, if you want, you also can set the style directly in your app.css
Based on your custom classname (.dataTables_wrapper) I think that this css should work.
.dataTables_wrapper .rdt_TableCell{
font-size:25px;
}
this is the className used by react-data-table-component
rdt_Table
rdt_TableRow
rdt_TableCol
rdt_TableCol_Sortable
rdt_TableCell
rdt_TableHeader
rdt_TableFooter
rdt_TableHead
rdt_TableHeadRow
rdt_TableBody
rdt_ExpanderRow
Related
I'm using the AntD tree and I have a react element that I want to pass as either an icon or a title because it has custom styling. Due to it being IP I can't share too much code, but my question is:
how can I pass a react element (see below i.e. generic name) as either a title or icon and have antD tree render it?
i.e. this is what I want to pass as a prop to the icon or title
import React from 'react';
const genericName = (props) => {
// code uses props to get some infor for Color
// cant share code due to proprietary reasons
// but it is not needed for this question
const colorHTML = getColor(Color);
return (
<div>
<div className={`colors from`}>${colorHTML}</div>
{pin}
</div>
);
};
export default genericName;
in my console you can see node.icon is a typeof react.element. I want to target that and just pass the prop into antD tree as either title or icon
i.e.
return (
<Tree
icon={node.icon}
/>
)
I've searched and similar answers were given before antD forbid the use of children and strictly allows treeData. All examples I see only use strings in titles/icons, but since antD documentation is very limited, I need to know if my use case is possible. Right now, for the life of me I can't understand why it doesn't populate.
Thank you in advance.
It should definitely work to put a JSX component as title within treeData. Take a look at this snippet, I added a Icon here in one of the titles:
import React from 'react'
import { RightCircleOutlined } from '#ant-design/icons'
type Props = {}
import { Tree } from 'antd';
import type { DataNode, TreeProps } from 'antd/es/tree';
const treeData: DataNode[] = [
{
title: <span>{<RightCircleOutlined />} parent</span>, //icon added here
key: '0-0',
children: [
{
title: 'parent 1-0',
key: '0-0-0',
disabled: true,
children: [
{
title: 'leaf',
key: '0-0-0-0',
disableCheckbox: true,
},
{
title: 'leaf',
key: '0-0-0-1',
},
],
},
{
title: 'parent 1-1',
key: '0-0-1',
children: [{ title: <span style={{ color: '#1890ff' }}>sss</span>, key: '0-0-1-0' }],
},
],
},
];
const Demo: React.FC = () => {
const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
console.log('selected', selectedKeys, info);
};
const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {
console.log('onCheck', checkedKeys, info);
};
return (
<Tree
checkable
defaultExpandedKeys={['0-0-0', '0-0-1']}
defaultSelectedKeys={['0-0-0', '0-0-1']}
defaultCheckedKeys={['0-0-0', '0-0-1']}
onSelect={onSelect}
onCheck={onCheck}
treeData={treeData}
/>
);
};
export default Demo;
How do I get imported data from importFile.js into dataTable.js?
https://github.com/Romson/CSV-file-uploader/blob/master/src/components/importFile.js
https://github.com/Romson/CSV-file-uploader/blob/master/src/components/dataTable.js
Tried this function to change nested arrays in imported data from importFile.js into a object of arrays.
const newArray = [data].map(
([firstName, lastName, issueCount, dateOfBirth]) => ({
firstName,
lastName,
issueCount,
dateOfBirth
})
);
Then a push into dataTable.js with:
data.rows.push(newArray);
What is the correct way to do this in React?
Expected result is to get the imported data to show in this table:
https://csv-file-uploader.herokuapp.com/
What you want to do is make DataTable component a child of Reader component. You need the array of object from Reader component for the rows property of datatable in DataTable component. As you said you are a beginner so better start from react hooks as it is easy.
Reader component
import React, {useState} from "react";
import CSVReader from "react-csv-reader";
import DatatablePage from "./dataTable";
import "../index.css";
const Reader = () => {
const [data, setData] = useState([]);
return (
<div className="container">
<CSVReader
cssClass="react-csv-input"
label="Upload a new CSV file"
onFileLoaded={(data) => setData(data)}
/>
<DatatablePage uploadedData={data} />
</div>
);
}
export default Reader;
DatatablePage component
import React from "react";
import { MDBDataTable } from "mdbreact";
const DatatablePage = ({uploadedData}) => {
const data = {
columns: [
{
label: "First Name",
field: "name",
sort: "asc",
width: 150
},
{
label: "Last Name",
field: "surname",
sort: "asc",
width: 270
},
{
label: "Issue count",
field: "issuecount",
sort: "asc",
width: 200
},
{
label: "Date of birth",
field: "dateofbirth",
sort: "asc",
width: 100
}
],
rows: []
};
// we append the passed props in the rows. read about spread operator if unaware of it.
const datatableProps = {...data, rows: uploadedData};
return <MDBDataTable striped bordered hover uploadedData={uploadedData} data={datatableProps} />;
};
export default DatatablePage;
We are using react hooks to create a state variable named data and a setter for it. Then we pass this state variable to the child component which can render it.
My backend service(elasticsearch percolator) annotates text with html tags to highlight matches.
I can't find a way to display such html data in antd Table.
I've tried Highlighter component, but it applies keywords to whole column, but I need to highlight different words in each row.
link to fiddle
const { Table } = antd
class TableColor extends React.Component {
constructor (props) {
super(props)
this.state = {
data: []
}
}
componentDidMount() {
this.setState({
data: [
{id:1, name: 'Lazy < bclass="myBackgroundColor">fox</b>', match: 'fox'},
{id:2, name: '<b class="myBackgroundColor">Dog</b> runs', match: 'Dog'},
{id:3, name: 'I saw <b class="myBackgroundColor">duck</b>', match: 'duck'}
]
})
}
render () {
const columns = [{
title: 'ID',
dataIndex: 'id',
}, {
title: 'Name',
dataIndex: 'name',
}, {
title: 'Match',
dataIndex: 'match',
}]
return (
<div style={{padding: '20px'}}>
<Table
columns={columns}
dataSource={this.state.data}
/>
</div>
)
}
}
ReactDOM.render(<TableColor />, document.querySelector('#app'))
Since it looks like the name column already has highlighted html you could just add a render property to the name column definition that uses dangerouslySetInnerHtml to render the raw html.
...something like:
render: function(html) { return <div dangerouslySetInnerHtml({__html: html}) />
https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
https://ant.design/components/table/#Column
If you wanted to use react-highlight-words you could do the same thing with a render property but use the second argument passed to that function to get the .match property of the record and use that as the highlighted word.
I want to render a component when a row is clicked in a react-table. I know i can use a subcomponent to achieve this but that doesn't allow click on the entire row. I want the subcomponent to render when the user clicks anywhere on that row. From their github page i understand that i want to edit getTdProps but am not really able to achieve it. Also the subcomponent is form and on the save of that form i want to update that row to reflect the changes made by the user and close the form. Any help is appreciated.
import React, {Component} from 'react';
import AdomainRow from './AdomainRow'
import ReactTable from "react-table"
import AdomainForm from './AdomainForm'
import 'react-table/react-table.css'
export default class AdomianTable extends Component {
render() {
const data = [{
adomain: "Reebok1.com",
name: "Reebok",
iabCategories: ["IAB1", "IAB2", "IAB5"],
status: "PENDING",
rejectionType: "Offensive Content",
rejectionComment: "The content is offensive",
isGeneric: false,
modifiedBy: "Sourav.Prem"
},
{
adomain: "Reebok2.com",
name: "Reebok",
iabCategories: ["IAB1", "IAB2", "IAB5"],
status: "PENDING",
rejectionType: "Offensive Content",
rejectionComment: "The content is offensive",
isGeneric: false,
modifiedBy: "Sourav.Prem"
},
{
adomain: "Reebok3.com",
name: "Reebok",
iabCategories: ["IAB1", "IAB2", "IAB5"],
status: "PENDING",
rejectionType: "Offensive Content",
rejectionComment: "The content is offensive",
isGeneric: false,
modifiedBy: "Sourav.Prem"
}];
//FOR REACT TABLE TO WORK
const columns = [{
Header : 'Adomian',
accessor : 'adomain'
}, {
Header : 'Name',
accessor : 'name'
}, {
Header : 'IABCategories',
accessor : 'iabCategories',
Cell : row => <div>{row.value.join(", ")}</div>
}, {
Header : 'Status',
accessor : 'status'
}];
return (
<div>
<ReactTable
getTdProps={(state, rowInfo, column, instance) => {
return {
onClick: (e, handleOriginal) => {
<AdomainForm row={rowInfo} ></AdomainForm>
console.log('A Td Element was clicked!')
console.log('it produced this event:', e)
console.log('It was in this column:', column)
console.log('It was in this row:', rowInfo)
console.log('It was in this table instance:', instance)
// IMPORTANT! React-Table uses onClick internally to trigger
// events like expanding SubComponents and pivots.
// By default a custom 'onClick' handler will override this functionality.
// If you want to fire the original onClick handler, call the
// 'handleOriginal' function.
if (handleOriginal) {
handleOriginal()
}
}
}
}}
data={data.adomains}
columns={columns}
defaultPageSize={10}
className="footable table table-stripped toggle-arrow-tiny tablet breakpoint footable-loaded"
SubComponent = { row =>{
return (
<AdomainForm row={row} ></AdomainForm>
);
}}
/>
</div>
);
}
}
}
I ran into the same issue where I wanted the entire row to be a clickable expander as React Table calls it. What I did was simply change the dimensions of the expander to match the entire row and set a z-index ahead of the row. A caveat of this approach is that any clickable elements you have on the row itself will now be covered by a full width button. My case had display only elements in the row so this approach worked.
.rt-expandable {
position: absolute;
width: 100%;
max-width: none;
height: 63px;
z-index: 1;
}
To remove the expander icon you can simply do this:
.rt-expander:after {
display: none;
}
I found it was better to add a classname to the react table:
<AdvancedExpandReactTable
columns={[
{
Header: InventoryHeadings.PRODUCT_NAME,
accessor: 'productName',
},
]}
className="-striped -highlight available-inventory" // custom classname added here
SubComponent={({ row, nestingPath, toggleRowSubComponent }) => (
<div className={classes.tableInner}>
{/* sub component goes here... */}
</div>
)}
/>
Then modify the styles so that the columns line up
.available-inventory .-header,
.available-inventory .-filters {
margin-left: -40px;
}
And then modify these styles as Sven suggested:
.rt-tbody .rt-expandable {
cursor: pointer;
position: absolute;
width: 100% !important;
max-width: none !important;
}
.rt-expander:after{
display: none;
}
I am using react-data-grid component. It provides a grid structure with edit and lot more options. When we click on each cell, we are able to edit the content of the cell. In my project, I have a situation like when the date column is focused I want to bind a UI where the user can able to select the date.for that, I have used react-datepicker component. I am able to give react-datepicker component as a formatter in the date column option. I can able to change the date in the react datepicker component, but that is not updating the cell value (when you click on the console data button you can able to see the changes have been updated or not).so guys help me how I can update the cell value when a different date is selected in the react-datepicker component. It happening automatically when the value is changed in other cells.
import React from 'react';
import ReactDOM from 'react-dom';
import ReactDataGrid from 'react-data-grid';
import DatePicker from 'react-datepicker';
import moment from 'moment';
//helper to generate a random date
function randomDate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())).toLocaleDateString();
}
//helper to create a fixed number of rows
function createRows(numberOfRows){
var _rows = [];
for (var i = 1; i < numberOfRows; i++) {
_rows.push({
id: i,
task: 'Task ' + i,
startDate: randomDate(new Date(2015, 3, 1), new Date())
});
}
return _rows;
}
//function to retrieve a row for a given index
var rowGetter = function(i){
return _rows[i];
};
//renders react datepicker component
var ExampleDate = React.createClass({
displayName: 'Example',
getInitialState: function() {
return {
startDate:moment(this.props.value,"MM-DD-YYYY")
};
},
consoleDate:function(){
console.log(this.state.startDate);
},
handleChange: function(date) {
this.setState({
startDate: date
});
},
render: function() {
return (
<div>
<DatePicker selected={this.state.startDate} onChange={this.handleChange} />
</div>
);
}
});
//Columns definition
var columns = [
{
key: 'id',
name: 'ID',
width: 80
},
{
key: 'task',
name: 'Title',
editable : true,
width:100
},
{
key: 'startDate',
name: 'Start Date',
editable : true,
formatter:<ExampleDate />,
width:100
}
]
var Example = React.createClass({
getInitialState : function(){
return {rows : createRows(5)}
},
rowGetter : function(rowIdx){
return this.state.rows[rowIdx]
},
handleRowUpdated : function(e){
//merge updated row with current row and rerender by setting state
var rows = this.state.rows;
Object.assign(rows[e.rowIdx], e.updated);
this.setState({rows:rows});
},
output:function(){
console.log(this.state.rows);
},
render:function(){
return(
<div>
<ReactDataGrid
enableCellSelect={true}
columns={columns}
rowGetter={this.rowGetter}
rowsCount={this.state.rows.length}
minHeight={200}
onRowUpdated={this.handleRowUpdated} />
<button onClick={this.output} > Console data </button>
</div>
)
}
});
ReactDOM.render(<Example />, document.getElementById('container'));
I encounter some issues when I tried to reproduce. Anyway, after some changes I works fine:
- I removed the random date to avoid "Invalid Date"
- I fixed the formatter like this
formatter: ({value}) => <ExampleDate value={value} />
All works fine, but I always get the warning, because of the key props of your columns :(