React table rendering in the form of a row - reactjs

Kind of a React noobie here so please don't judge.
The react table is rendering in the form of a row.
My Component:
import React, { Component } from 'react';
import ReactTable from 'react-table';
// import 'react-table/react-table.css';
class Variants extends Component {
constructor(props) {
super(props);
}
render() {
const columns = [
{
Header: 'Gene',
accessor: 'gene'
},
{
Header: 'Nucleotide Change',
accessor: 'nucleotide_change'
},
{
Header: 'Protein Change',
accessor: 'protein_change'
},
{
Header: 'Other Mappings',
accessor: 'other_mappings'
},
{
Header: 'Alias',
accessor: 'alias'
},
{
Header: 'Transcripts',
accessor: 'transcripts'
},
{
Header: 'Region',
accessor: 'region'
},
{
Header: 'Reported Classification',
accessor: 'reported_classification'
},
{
Header: 'Inferred Classification',
accessor: 'inferred_classification'
},
{
Header: 'Source',
accessor: 'source'
},
{
Header: 'Last Evaluated',
accessor: 'last_evaluated'
},
{
Header: 'Last Updated',
accessor: 'last_updated'
},
{
Header: 'More Information',
accessor: 'url',
Cell: e => (
<a target="_blank" href={e.value}>
{' '}
{e.value}{' '}
</a>
)
},
{
Header: 'Submitter Comment',
accessor: 'submitter_comment'
}
];
if (this.props.variants && this.props.variants.length > 0) {
return (
<div>
<h2>
{' '}
There are {this.props.variants.length} variants of this gene!
</h2>
<div>
<ReactTable
data={this.props.variants}
columns={columns}
defaultPageSize={3}
pageSizeOptions={[3, 5, 10, 50, 100]}
/>
</div>
</div>
);
} else {
return [];
}
}
}
export default Variants;
It is rendering the whole table as a row for some weird reason. I have attached the image to show what is happening. Also, the pagination buttons are not nice. Can they be modified?
Has anyone come across a similar problem?

I got it working below. I simplified the data since you didn't provide an example data set but this should help you.
The only thing I can think you have wrong is either you need to uncomment import 'react-table/react-table.css'; or maybe you are passing in your props wrong in <Variants variants={variants}/>
Variants.js
import React, { Component } from 'react';
import ReactTable from 'react-table';
import 'react-table/react-table.css';
class Variants extends Component {
render() {
const columns = [
{
Header: 'Gene',
accessor: 'gene'
},
{
Header: 'Nucleotide Change',
accessor: 'nucleotide_change'
},
{
Header: 'Protein Change',
accessor: 'protein_change'
}
];
if (this.props.variants && this.props.variants.length > 0) {
return (
<div>
<h2>
{' '}
There are {this.props.variants.length} variants of this gene!
</h2>
<div>
<ReactTable
data={this.props.variants}
columns={columns}
defaultPageSize={3}
pageSizeOptions={[3, 5, 10, 50, 100]}
/>
</div>
</div>
);
} else {
return [];
}
}
}
export default Variants;
App.js
import React from 'react';
import './App.css';
import Variants from "./Variants";
const variants = [
{
gene:'a',
nucleotide_change:'a',
protein_change:'a'
},
{
gene:'b',
nucleotide_change:'b',
protein_change:'b'
}
];
function App() {
return (
<div className="App">
<Variants variants={variants}/>
</div>
);
}
export default App;

Related

Adding colDefs dynamically

I'm trying to add the column definition programmatically,on button click, instead of hardcoding it in my ReactJS page.
{
headerName: "Product1",
resizable: true,
wrapText: true,
cellStyle: {
'white-space': 'normal'
},
autoHeight: true,
hide: true,
cellRendererFramework.MyCustomColumnRenderer
}
Not sure how to go about implementing this?
Thanks for your help.
Use setColumnDefs(columnDefs)
const columnDefs = getColumnDefs();
columnDefs.forEach(function (colDef, index) {
colDef.headerName = 'Abcd';
});
this.gridApi.setColumnDefs(columnDefs);
https://plnkr.co/edit/0ctig4P2yzPjhycB
You could define the columnDefs in the grid to use a state and then set the state dynamically.
import React from 'react';
import { render } from 'react-dom';
import { AgGridColumn, AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';
const App = () => {
const rowData = [
{ make: 'Toyota', model: 'Celica', price: 35000 },
{ make: 'Ford', model: 'Mondeo', price: 32000 },
{ make: 'Porsche', model: 'Boxter', price: 72000 },
];
// use the colDefs state to define the column definitions
const [colDefs, setColDefs] = React.useState([{ field: 'make' }]);
// when the button is pressed set the state to cause the grid to update
const handleAddColumns = ()=> {
const dynamicFields = [
{ field: 'make', header: 'Car Make' },
{ field: 'model', sortable: true },
{ field: 'price' },
];
setColDefs(dynamicFields);
}
return (
<div>
<button onClick={handleAddColumns}>Add Column Defs</button>
<div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
<AgGridReact
rowData={rowData}
columnDefs={colDefs}>
</AgGridReact>
</div>
</div>
);
};
render(<App />, document.getElementById('root'));
Another approach is to use the Api's setColumnDef method:
import React from 'react';
import { render } from 'react-dom';
import { AgGridColumn, AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';
const App = () => {
const rowData = [
{ make: 'Toyota', model: 'Celica', price: 35000 },
{ make: 'Ford', model: 'Mondeo', price: 32000 },
{ make: 'Porsche', model: 'Boxter', price: 72000 },
];
// using state to define the columns initially
const [colDefs, setColDefs] = React.useState([{ field: 'make' }]);
// get a reference to the API when the onGridReady is fired
// see the Grid definition in the JSX
const [gridApi, setGridApi] = React.useState([]);
const handleAddColumns = ()=> {
const dynamicFields = [
{ field: 'make', header: 'Car Make' },
{ field: 'model', sortable: true },
{ field: 'price' },
];
// use the API to set the Column Defs
gridApi.setColumnDefs(dynamicFields);
}
return (
<div>
<button onClick={handleAddColumns}>Add Column Defs</button>
<div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
<AgGridReact
rowData={rowData}
columnDefs={colDefs}
onGridReady={ params => {setGridApi(params.api)} }
></AgGridReact>
</div>
</div>
);
};
render(<App />, document.getElementById('root'));
The examples in the documentation should help:
https://www.ag-grid.com/react-data-grid/column-definitions/
https://www.ag-grid.com/react-data-grid/column-updating-definitions/
There is also a blog post from AG Grid that covers dynamic column definitions:
https://blog.ag-grid.com/binding-and-updating-column-definitions-in-ag-grid/

trying to implement a text filter to a ag-grid in a react component

I can't figure out how to implement a simple search bar to the ag-grid i set. I would like to let my input filter the results in my grid based on every columns I couldn't figure out a good documentation with example for that. Here is my code. Feel free to redirect me to a proper example or another question similar.
import React from 'react';
import { AgGridReact } from 'ag-grid-react';
import axios from 'axios';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';
class ListTableClients extends React.Component {
constructor(props) {
super(props);
this.state = {
defaultColDef: {
flex: 1,
cellClass: 'cell-wrap-text',
autoHeight: true,
sortable: true,
resizable: true,
},
columnDefs: [
{ headerName: "id", field: "id", maxWidth: 100 },
{ headerName: "name", field: "name"},
{ headerName: "email", field: "email"}],
rowData: [
{ id: 1, name: 'maison du café', email: 'maisonducafe#gamil.com' },
{ id: 2, name: 'Warehouse', email: 'contact#warehouse.fr' },
{ id: 3, name: 'Maestro', email: 'maestro#gmail.com' }],
rowHeight: 275,
}
}
componentDidMount() {
console.log('test');
axios.get('http://localhost:8080/listClients').then((res) => {
this.setState({ rowData: res.data });
}).catch((error) => { console.log(error) });
}
render() {
return (
<div style={{width: '100%', paddingLeft: '50px', paddingRight: '50px', paddingTop: '50px'}} className="ag-theme-alpine">
<input type="text" placeholder="Filter..." onInput={this.onFilterTextBoxChanged}/>
<AgGridReact
domLayout='autoHeight'
columnDefs={this.state.columnDefs}
defaultColDef={this.state.defaultColDef}
getRowHeight={this.state.getRowHeight}
rowData={this.state.rowData}>
</AgGridReact>
</div>
);
}
}
export default ListTableClients;
Refer this demo
If the cell data in object format then you have to format it Ag-Grid Value Formatters

The column with audio file playback from the file system does not change on sorting or paging

I'm new in React and I'm trying to create a simple react table - a list of records with audio file playback. Metadata about records are from database and the audio file is loaded according to the file_address column from the file system.
During sorting and paging, all table columns change, except the playback column, which does not change in general. I attached my code. Thank you in advance for your help :)
import React from 'react';
import ReactTable from 'react-table'
import 'react-table/react-table.css'
import './App.css';
import { Container } from "#material-ui/core";
import { maxHeight } from '#material-ui/system';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoaded: false,
error: null,
items: []
};
}
/**
* call BE endpoint to receive records data
*/
componentDidMount() {
fetch("/records")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.Records
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
/**play wav audio */
async play(file_address) {
var audio = new Audio({file_address});
audio.type = 'audio/wav';
try {
await audio.play();
console.log('Playing...');
} catch (err) {
console.log('Failed to play...' + err);
}
}
/**create table structure */
render(){
const items = this.state.items;
const columns = [{
Header: 'ID',
accessor: 'Id',
sortable: true
},
{
Header: 'Name',
accessor: 'Name',
sortable: true
},
{
id: 'Play',
Header: 'Play',
accessor: a => <audio controls>
<source src={a.File_Address} type="audio/wav" />
</audio>
},
{
Header: 'Duration',
accessor: 'Duration',
sortable: true
},
{
Header: 'Date',
accessor: 'Date',
sortable: true
},
{
Header: 'Time',
accessor: 'Time',
sortable: true
},{
Header: 'File address',
accessor: 'File_Address'
}
]
/**return react components with records data */
return (
<Container className="container" maxWidth="xl" style={{ height: maxHeight, background: '#ffffff', color: '#424242'}}>
<h1 className="title">Records</h1>
<ReactTable
style={{
background: '#eeeeee',
color: '#000000'
}}
data={items}
columns={columns}
/>
</Container>
)
}
}
export default App;

React-Table, each cell goes to a new line, why?

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";

*React-table* second page not showing data

I have a table which displays clinics. I have also a onPageChange prop which handles the pageIndex and then i fetch the data based on that page. Below is my table configuration
import 'react-table/react-table.css'
import React, { Component } from 'react';
import ClinicFormComponent from './newClinicForm';
import SearchFormComponent from '../search/searchForm';
import { connect } from 'react-redux';
import { fetchClinics, fetchClinic, deleteClinic, searchClinics, pushBreadcrumb, popBreadcrumb } from '../../actions/index.js';
import { toast } from 'react-toastify';
import ReactTable from 'react-table'
import store from '../../helpers/store';
import { ic_search } from 'react-icons-kit/md/ic_search';
import SvgIcon from 'react-icons-kit';
require('normalize.css/normalize.css');
// require('styles/App.css');
class ClinicsPage extends Component {
constructor() {
super();
this.handleClickForm = this.handleClickForm.bind(this);
this.handleClickFormSearch = this.handleClickFormSearch.bind(this);
this.closeForm = this.closeForm.bind(this);
this.onPageChange = this.onPageChange.bind(this);
}
componentDidMount(){
this.props.searchClinics({ country: 'Australia' });
}
onPageChange(pageIndex) {
this.props.fetchClinics(pageIndex, null);
}
render() {
let { devs } = this.props;
const columns = [{
Header: 'Id',
accessor: 'id' // String-based value accessors!
}, {
Header: 'Name',
accessor: 'name'
}, {
Header: 'Description', // Required because our accessor is not a string
accessor: 'description',
sortable: true
// accessor: d => d.friend.name // Custom value accessors!
},
{
Header: 'Country', // Required because our accessor is not a string
accessor: 'country',
sortable: true
// accessor: d => d.friend.name // Custom value accessors!
},
{
Header: 'Area', // Required because our accessor is not a string
accessor: 'area',
sortable: true
// accessor: d => d.friend.name // Custom value accessors!
},
{
Header: 'Latitude', // Required because our accessor is not a string
accessor: 'latitude',
sortable: true
// accessor: d => d.friend.name // Custom value accessors!
},
{
Header: 'Longitude', // Required because our accessor is not a string
accessor: 'longitude',
sortable: true
// accessor: d => d.friend.name // Custom value accessors!
},
{
Header: 'Tags', // Required because our accessor is not a string
accessor: 'tags',
sortable: true,
Cell: (row) => {if (row.original.tags.length>1) { return row.original.tags.join(', ') } else { return row.original.tags } }
},
{
Header: () => <span className="text-center">Actions</span>,
accessor: 'id',
id: 'actions',
sortable: true,
Cell: (row) => (<span><button className="text-center btn btn-primary-zoetis margin_right_5" onClick={()=>{this.props.history.push('/editClinic/'+ row.original.id)}}>Edit</button ><button className="text-center btn btn-danger" onClick={()=>{this.props.deleteClinic(row.original.id, row.original)}}>Delete</button ></span>)
}
]
return (
<div className="wrap">
<div className="row margin_top_10 margin_bottom_5">
<div className="col-sm-6">
<a className="btn btn-link color_zoetis btn_zoetis_alt" data-toggle="collapse" role="button" aria-expanded="false" aria-controls="collapseExample2" onClick={this.handleClickForm}>NEW CLINIC</a>
</div>
<div className="col-sm-6">
<a className="nav-link float_right search-clinic-btn" data-toggle="collapse" onClick={this.handleClickFormSearch} role="button" aria-expanded="false" aria-controls="collapseExample"><span className="search_label">Search data entries...</span> <SvgIcon size={25} icon={ic_search}/></a>
</div>
</div>
<div id="nav-tabContent">
<ReactTable
data={devs.clinics}
pageSizeOptions= {[10]}
defaultPageSize= {10}
columns={columns}
pages={devs.paginationData.totalPages || ''}
sortable={true}
multiSort={true}
//manual
filterable
page={devs.paginationData.pageNumber}
loading={devs.isFetching}
onPageChange={this.onPageChange}
noDataText='No Data Found'
className='-striped -highlight'
/>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
devs: state.reducer.devs,
showMenu: state.reducer.devs.showMenu,
showEditMenu: state.reducer.devs.showEditMenu,
paginationData: state.reducer.devs.paginationData,
location: state.router.location.pathname
}
}
export const mapDispatchToProps = {
fetchClinics,
searchClinics,
fetchClinic,
deleteClinic,
pushBreadcrumb,
popBreadcrumb
}
export default connect(mapStateToProps, mapDispatchToProps)(ClinicsPage);
Notice that i have disabled manual prop. If i enable the manual prop then i can navigate through next and previous pages but i cannot sort or filter the data.
With the manual prop disabled the filtering and the sorting works correct but when i navigate in the next page the table is showing empty. The first page displays correct the first 10 data. Also i have tested the api and returns correct the next 10 data.
Is there any workaround? To keep both server side pagination and alse the default sorting and filtering?
Test decomposing manual property
<ReactTable
filtered={this.state.filtered}
onFilteredChange={this.onFilteredChange.bind(this)}
defaultFilterMethod={(filter, row) =>
String(row[filter.id]) === filter.value
}
columns={columns}
ref={r => (this.selectTable = r)}
className="-striped -highlight"
defaultPageSize={10}
data={this.state.data}
pages={this.state.pages}
loading={this.state.loading}
manual <-------
resizable={true}
filterable
filterAll={true}
onFetchData={(state, instance) => {
this.setState({loading: true})
axios.get(`${API}${controller}`, {
params: {
pages: state.page,
pageSize: state.pageSize,
filtered: state.filtered,
typeOption: `${type}`,
dateinit: `${this.state.dateinit}`,
datefinal: `${this.state.datefinal}`,
data: this.props.data
},
headers: { 'Authorization': `${tokenCopyPaste()}` }
})
.then((res) => {
this.props.exportTable(res.data, type);
this.setState({
data: res.data.data,
fulldata: res.data,
pages: Math.ceil(res.data.pages / state.pageSize),
loading: false
})
})
}
}
/>

Resources