Export react table as csv - javascript

Hi guys I'm trying to export my atlassian dynamic react table as a csv file but the table I'm getting in the file is not really looking as I expected... I tried using the react-csv library but I'm getting . My dynamic table looks like this on my browser. The Columns are in {shareFilterHead} and the rows are {shareFilterRows} . Is there any other way to download this table in React as a csv file?
import React, {Component} from "react";
import DynamicTable from '#atlaskit/dynamic-table';
import styled from 'styled-components';
import { CSVLink, CSVDownload } from "react-csv";
export const createHead = (withWidth) => {
return {
cells: [
{
key: 'filterID',
content: 'Filter ID',
isSortable: true,
width: withWidth ? 25 : undefined,
fontSize: 30,
},
{
key: 'author',
content: 'Author',
shouldTruncate: true,
isSortable: true,
width: withWidth ? 25 : undefined,
fontSize: 30,
},
{
key: 'filtername',
content: 'Filter Name',
shouldTruncate: true,
isSortable: true,
width: withWidth ? 25 : undefined,
fontSize: 30,
},
{
key: 'jql',
content: 'JQL',
shouldTruncate: true,
isSortable: true,
width: withWidth ? 25 : undefined,
fontSize: 30,
},
],
};
};
export const shareFilterHead = createHead(true);
export default class ShareFilter extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
shareFilterRows: []
};
}
componentDidMount() {
fetch(AJS.contextPath() + "/rest/securityrestresource/1.0/results?check=ShareFilter")
.then((res)=>{
if(res.ok) {
return res.json();
}
}).then((res)=>{
this.setState({
isLoaded: true,
shareFilterRows: res.map((row, index) => ({
key: `row-${index}-${row.filterID}`,
cells: [{
key: `${row.filterID}`,
content: row.filterID,
},
{
key: `${row.author}`,
content: row.author,
},
{
key: `${row.filtername}`,
content: row.filtername,
},
{
key: `${row.jql}`,
content: row.jql,
},]}))
})
})
}
render() {
const { error, isLoaded, shareFilterRows } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading Shared Filters...</div>;
} else {
return (
<Wrapper>
<div>
<DynamicTable
head={shareFilterHead}
rows={shareFilterRows}
rowsPerPage={10}
defaultPage={1}
loadingSpinnerSize="large"
isLoading={false}
isFixedSize
defaultSortKey="filterID"
defaultSortOrder="ASC"
onSort={() => console.log('onSort')}
onSetPage={() => console.log('onSetPage')}
/>
<CSVDownload data={shareFilterRows} target="_blank" />;
</div>
</Wrapper>
);
}
}
}

Related

Malformed or invalid request: Clarifai Api

import React from 'react';
import './App.css';
import Navigation from './components/Navigation/Navigation'
import ImageLinkForm from './components/ImageLinkForm/ImageLinkForm'
import FaceRecognition from './components/FaceRecognition/FaceRecognition'
import Rank from './components/Rank/Rank'
import Logo from './components/Logo/Logo'
import Clarifai from 'clarifai'
import Particles from 'react-tsparticles';
const particlesOptions = {
particles: {
color: {
value: "#ffffff",
},
links: {
color: "#ffffff",
distance: 150,
enable: true,
opacity: 0.5,
width: 1,
},
collisions: {
enable: true,
},
move: {
direction: "none",
enable: true,
outMode: "bounce",
random: false,
speed: 6,
straight: false,
},
number: {
density: {
enable: true,
area: 500,
},
value: 100,
},
opacity: {
value: 0.5,
},
shape: {
type: "circle",
},
size: {
random: true,
value: 2,
},
},
detectRetina: true,}
//clarifai API
const app = new Clarifai.App({
apiKey: 'a2013f7d2d54452d9592d7569ce4c5bd'
});
class App extends React.Component {
constructor (){
super();
this.state = {
input : '',
imageUrl : ''
}
}
onInputChange = (event) => {
this.setState({input: event.target.value})
}
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input});
app.models.predict(Clarifai.FACE_DETECT_MODEL, this.state.input).then(
function(response) {
// do something with response
console.log(response);
},
function(err) {
// there was an error
}
);
}
render(){
return (
<div className="App">
<Particles className='particles'
id="tsparticles"
options={particlesOptions}
/>
<Navigation />
<Logo />
<Rank />
<ImageLinkForm onInputChange = {this.onInputChange} onButtonSubmit = {this.onButtonSubmit}/>
<FaceRecognition imageUrl = {this.state.imageUrl}/>
</div>
);}
}
export default App;
Whenever I am running this code, I am getting 'Invalid request' but if someone else is running the same code, there is no error and the code is working fine. I have tried changing multiple time but no solution found please help.
Response Error: {"status":{"code":11102,"description":"Invalid request","details":"Malformed or invalid request"}}
Github repo: https://github.com/devgobind/smart-recognition-brain

How to return JSON object in Javascript?

I am having issues with returning a JSON object. When I render the webpage, nothing shows up. Does anyone know how to fix this? Sorry, I am new to Javascrtipt.
import React, { useEffect, useState, useContext } from 'react'
export const MarketData = () => {
var obj = {
width: '100%',
height: '100%',
symbolsGroups: [
{
name: 'Indices',
originalName: 'Indices',
symbols: [
{
name: 'INDEX:DEU30',
displayName: 'DAX Index',
},
{
name: 'FOREXCOM:UKXGBP',
displayName: 'FTSE 100',
},
],
},
...
],
showSymbolLogo: true,
colorTheme: 'dark',
isTransparent: false,
locale: 'en',
largeChartUrl:
'https://bondintelligence.cloud.looker.com/extensions/bond_intelligence_webpage::helloworld-js/',
}
return (
<>
<text>{obj}</text>
</>
)
}
You can use JSON.stringify()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The third argument in JSON.stringify() provides new lines and indentation. If only the first argument is provided, the string will be one long line.
Your example with fix (I changed your <text> to <p> as I have never heard of a <text> HTML element):
import React, { useEffect, useState, useContext } from 'react'
export const MarketData = () => {
var obj = {
width: '100%',
height: '100%',
symbolsGroups: [
{
name: 'Indices',
originalName: 'Indices',
symbols: [
{
name: 'INDEX:DEU30',
displayName: 'DAX Index',
},
{
name: 'FOREXCOM:UKXGBP',
displayName: 'FTSE 100',
},
],
},
...
],
showSymbolLogo: true,
colorTheme: 'dark',
isTransparent: false,
locale: 'en',
largeChartUrl:
'https://bondintelligence.cloud.looker.com/extensions/bond_intelligence_webpage::helloworld-js/',
}
var objAsString = JSON.stringify(obj, null, 2)
return (
<>
<p>{objAsString}</p>
</>
)
}

How to render a material-table using a JSON that comes from a API response?

I'm new on ReactJS and this is my first page that I created, but I'm having some problems with set variables.
What I need is fill the variable table.data with the values that comes from const response = await api.get('/users') and render the table with this values when page loads.
I have the following code:
import React, { useState, useEffect } from 'react';
import { Fade } from "#material-ui/core";
import MaterialTable from 'material-table';
import { makeStyles } from '#material-ui/core/styles';
import api from '../../services/api.js';
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
width: '70%',
margin: 'auto',
marginTop: 20,
boxShadow: '0px 0px 8px 0px rgba(0,0,0,0.4)'
}
}));
function User(props) {
const classes = useStyles();
const [checked, setChecked] = useState(false);
let table = {
data: [
{ name: "Patrick Mahomes", sector: "Quaterback", email: "patrick#nfl.com", tel: "1234" },
{ name: "Tom Brady", sector: "Quaterback", email: "tom#nfl.com", tel: "5678" },
{ name: "Julio Jones", sector: "Wide Receiver", email: "julio#nfl.com", tel: "9876" }
]
}
let config = {
columns: [
{ title: 'Name', field: 'name' },
{ title: 'Sector', field: 'sector' },
{ title: 'E-mail', field: 'email'},
{ title: 'Tel', field: 'tel'}
],
actions: [
{ icon: 'create', tooltip: 'Edit', onClick: (rowData) => alert('Edit')},
{ icon: 'lock', tooltip: 'Block', onClick: (rowData) => alert('Block')},
{ icon: 'delete', tooltip: 'Delete', onClick: (rowData) => alert('Delete')},
{ icon: 'visibility', tooltip: 'Access', onClick: (rowData) => alert('Access')},
{ icon: "add_box", tooltip: "Add", position: "toolbar", onClick: () => { alert('Add') } }
],
options: {
headerStyle: { color: 'rgba(0, 0, 0, 0.54)' },
actionsColumnIndex: -1,
exportButton: true,
paging: true,
pageSize: 10,
pageSizeOptions: [],
paginationType: 'normal'
},
localization: {
body: {
emptyDataSourceMessage: 'No data'
},
toolbar: {
searchTooltip: 'Search',
searchPlaceholder: 'Search',
exportTitle: 'Export'
},
pagination: {
labelRowsSelect: 'Lines',
labelDisplayedRows: '{from} to {to} for {count} itens',
firstTooltip: 'First',
previousTooltip: 'Previous',
nextTooltip: 'Next',
lastTooltip: 'Last'
},
header: {
actions: 'Actions'
}
}
}
useEffect(() => {
setChecked(prev => !prev);
async function loadUsers() {
const response = await api.get('/users');
table.data = response.data;
}
loadUsers();
}, [])
return (
<>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<Fade in={checked} style={{ transitionDelay: checked ? '300ms' : '0ms' }}>
<div className={classes.root}>
<MaterialTable editable={config.editable} options={config.options} localization={config.localization} title="Usuários" columns={config.columns} data={table.data} actions={config.actions}></MaterialTable>
</div>
</Fade>
</>
);
}
export default User;
The previous example will show 3 users that I fixed on variable table.data with 4 columns (name, sector, email, tel).
In a functional component, each render is really a new function call. So any variables you declare inside the component and destroyed and re-created. This means that table is set back to your initial value each render. Even if your useEffect is setting it correctly after the first render, it will just be reset on the next.
This is what state is for: to keep track of variables between renders. Replace your let table, with a new state hook.
const [table, setTable] = useState({
data: [
{ name: "Patrick Mahomes", sector: "Quaterback", email: "patrick#nfl.com", tel: "1234" },
{ name: "Tom Brady", sector: "Quaterback", email: "tom#nfl.com", tel: "5678" },
{ name: "Julio Jones", sector: "Wide Receiver", email: "julio#nfl.com", tel: "9876" }
]
});
Then use it like this:
useEffect(() => {
setChecked(prev => !prev);
async function loadUsers() {
const response = await api.get('/users');
setTable(prev => ({...prev, data: response.data});
}
loadUsers();
}, [])
Since table.data is not a state variable, it is regenerated as it was declared originally every time the component renders, meaning that by the time it arrives as a prop to your component it will always be the same value (when you change the value of table.data in useEffect it is too late). You need to change table.data to a state variable, and then in your useEffect hook you can update the value of table.data to the value of response.data. This will cause the component to be re-rendered but with the updated value.
Here's an example of how you might do that:
import React, { useState, useEffect } from 'react';
import { Fade } from "#material-ui/core";
import MaterialTable from 'material-table';
import { makeStyles } from '#material-ui/core/styles';
import api from '../../services/api.js';
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
width: '70%',
margin: 'auto',
marginTop: 20,
boxShadow: '0px 0px 8px 0px rgba(0,0,0,0.4)'
}
}));
function User(props) {
const classes = useStyles();
const [checked, setChecked] = useState(false);
const [tableData, setTableData] = useState([]);
let config = {
columns: [
{ title: 'Name', field: 'name' },
{ title: 'Sector', field: 'sector' },
{ title: 'E-mail', field: 'email'},
{ title: 'Tel', field: 'tel'}
],
actions: [
{ icon: 'create', tooltip: 'Edit', onClick: (rowData) => alert('Edit')},
{ icon: 'lock', tooltip: 'Block', onClick: (rowData) => alert('Block')},
{ icon: 'delete', tooltip: 'Delete', onClick: (rowData) => alert('Delete')},
{ icon: 'visibility', tooltip: 'Access', onClick: (rowData) => alert('Access')},
{ icon: "add_box", tooltip: "Add", position: "toolbar", onClick: () => { alert('Add') } }
],
options: {
headerStyle: { color: 'rgba(0, 0, 0, 0.54)' },
actionsColumnIndex: -1,
exportButton: true,
paging: true,
pageSize: 10,
pageSizeOptions: [],
paginationType: 'normal'
},
localization: {
body: {
emptyDataSourceMessage: 'No data'
},
toolbar: {
searchTooltip: 'Search',
searchPlaceholder: 'Search',
exportTitle: 'Export'
},
pagination: {
labelRowsSelect: 'Lines',
labelDisplayedRows: '{from} to {to} for {count} itens',
firstTooltip: 'First',
previousTooltip: 'Previous',
nextTooltip: 'Next',
lastTooltip: 'Last'
},
header: {
actions: 'Actions'
}
}
}
useEffect(() => {
setChecked(prev => !prev);
async function loadUsers() {
const response = await api.get('/users');
setTableData(response.data);
}
loadUsers();
}, [])
return (
<>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<Fade in={checked} style={{ transitionDelay: checked ? '300ms' : '0ms' }}>
<div className={classes.root}>
<MaterialTable editable={config.editable} options={config.options} localization={config.localization} title="Usuários" columns={config.columns} data={tableData} actions={config.actions}></MaterialTable>
</div>
</Fade>
</>
);
}
export default User;

How to show the data I got from API to react-material datatable

I'm new when using materialUI table in react.js, I want to try using react-material table but I got lost as how can I show my data in the table, Let say I have 28 data and in fact it already show the right number in the pagination but the data itself doesn't show anything. this is the documentation link for react-material table Check this.
I already read several topic about this but all of them using tableRow, tableHead, and etc.
this is my component code:
import React, { Component } from 'react';
import MaterialTable from 'material-table';
import { history } from '../../../../Helpers/history';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { orderActions } from '../../../../Actions/orderActions';
import { withStyles } from '#material-ui/core/styles';
// Component
import './tabledata.css';
const styles = theme => ({
'#global': {
body: {
backgroundColor: theme.palette.common.white,
},
},
});
class Tabledata extends Component {
constructor(props) {
super(props);
// const { orders } = this.props;
this.state = {
columns: [
{ title: 'Nama Pemesanan', field: 'name' },
{ title: 'Status', field: 'status' },
{ title: 'Estimasi Pengerjaan (Hari)', field: 'estimate', type: 'numeric' },
{ title: 'Jumlah Pesanan (pcs)', field: 'unit', type: 'numeric' },
{ title: 'Harga (Rp)', field: 'price', type: 'numeric' },
],
data: [
{
id: 2,
name: 'lala',
status: 'Penyablonan',
estimate: 8,
unit: 36,
price: '36.000.000',
},
],
}
}
componentDidMount() {
if(localStorage.getItem('auth')) {
const { dispatch } = this.props;
dispatch(orderActions.getAllOrder());
// history.push('/dashboard');
}
}
componentWillReceiveProps(newProps){
this.setState({ loading: newProps.loading }); // remove the loading progress when logged in or fail to log in
}
handleChange = prop => event => {
this.setState({ [prop]: event.target.value });
};
change(data){
console.log("Check ID : ", data);
}
render(){
const { orders } = this.props;
console.log("test console : ", orders)
return (
<div className="tabledata-order">
<div className="row item-section">
<div className="col">
<div className="card">
<div className="card-body">
<MaterialTable
title="Daftar Pesanan"
columns={this.state.columns}
key={orders._id}
data={orders}
/>
</div>
</div>
</div>
</div>
</div>
);
}
}
Tabledata.propTypes = {
classes: PropTypes.object.isRequired
};
const mapStateToProps = (state) => {
const { orders } = state.orderPage;
return {
orders
};
}
const connectedTableDataPage = withRouter(connect(mapStateToProps, '', '', {
pure: false
}) (withStyles(styles)(Tabledata)));
export { connectedTableDataPage as Tabledata };
As you can see, this material table have a component like this
<MaterialTable
title="Daftar Pesanan"
columns={this.state.columns}
key={orders._id}
data={orders}
/>
As you can see, in the bottom of the image you can see 1-5 of 28 and in my console there is exactly 28 data but the table itself doesn't show any data
can someone help me? how can I show the data in orders and this is the example of the image json that I have:
Finally I can fix this problem, this answer for you who have facing the same problem with react-material table if your data doesn't show but it show in console.log. you must check the field in column
this.state = {
columns: [
{ title: 'Nama Pemesanan', field: 'name' },
{ title: 'Status', field: 'status' },
{ title: 'Estimasi Pengerjaan (Hari)', field: 'estimate', type: 'numeric' },
{ title: 'Jumlah Pesanan (pcs)', field: 'unit', type: 'numeric' },
{ title: 'Harga (Rp)', field: 'price', type: 'numeric' },
],
data: [
{
id: 2,
name: 'lala',
status: 'Penyablonan',
estimate: 8,
unit: 36,
price: '36.000.000',
},
],
}
let say, json that I got have city, color, and weight then you must state the column field as such:
this.state = {
columns: [
{ title: 'detail Address', field: 'city' },
{ title: 'color', field: 'color' },
{ title: 'weight', field: 'weight' },
],
}
and for the MaterialTable you can just put all the variable you have like this
<MaterialTable
title="Daftar Pesanan"
columns={this.state.columns}
key={orders._id}
data={orders}
/>
and you can get the data like I show you below
I hope this answer can help you who have a hard time with react-material table

How to add a button inside a react bootstrap table?

I'm trying to add a button to a cell in a react bootstrap table with the following is my code:
import React, { Component } from "react";
import BootstrapTable from "react-bootstrap-table-next";
import { Button } from 'reactstrap';
class ActionsCard extends Component {
constructor(props) {
super(props);
this.state = {
actions: [{action: "Upgrade device", details: "Upgrade device to version 0.1.1", _id: "1"}],
valid: true
};
this.columns = [
{
text: "Action",
dataField: "action",
sort: true,
editable: false,
headerStyle: (colum, colIndex) => {
return { width: "5%", textAlign: "left" };
}
},
{
text: "Details",
dataField: "details",
sort: true,
editable: false,
headerStyle: (colum, colIndex) => {
return { width: "12%", textAlign: "left" };
}
},
{
sort: true,
headerStyle: (colum, colIndex) => {
return { width: "16%", textAlign: "left" };
},
Header: 'Test',
Cell: cell => (
<Button onClick={() => console.log(cell.original)}>Upgrade</Button>
),
}
];
}
render() {
return (
<React.Fragment>
<BootstrapTable
keyField="_id"
data={this.state.actions}
columns={this.columns}
noDataIndication="No Interfaces available"
defaultSorted={[{ dataField: "action", order: "asc" }]}
/>
</React.Fragment>
);
}
}
export default ActionsCard;
However, when I run the code, the two first columns of the table appear as expected, but the third column is simply empty.
You can use formatter to add button as in this discussion mention
{
dataField: "databasePkey",
text: "Remove",
formatter: (cellContent: string, row: IMyColumnDefinition) => {
if (row.canRemove)
return <button className="btn btn-danger btn-xs" onClick={() => this.handleDelete(row.databasePkey)}>Delete</button>
return null
},
},

Categories

Resources