React Hooks in TypeScript to Classes - reactjs

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

Related

TableRow: Unexpected any. Specify a different type

Building a Table component using TS followed this to type everything as needed.
But as I broke down the row in it's separate component i am unable to type it properly.
export interface ITableRow<DataType> {
rowData: any; // The Issue is with this line
columnKeys: Array<DataType>;
}
function getTableRow<T>({ rowData, columnKeys }: ITableRow<T>) {
return columnKeys.map((columnKey, index) => (
<td key={index}>{rowData[columnKey]}</td>
));
}
export function TableRow<T>({ rowData, columnKeys }: ITableRow<T>) {
const tableRow = getTableRow({ rowData, columnKeys });
return <tr>{tableRow}</tr>;
}
The rowData prop is an object that can have any number of keys as specified in the headers object
for example:
const heads = [
{
id: 'company',
label: 'Company'
},
{
id: 'nb_employees',
label: 'Number of employees'
},
{
id: 'country',
label: 'Country'
}
];
const rows = [
{
company: 'Vody aho',
nb_employees: 1590,
country: 'Hong Kong'
},
{
company: 'Royal spirit',
nb_employees: 15,
country: 'USA'
},
];
How do I type the rowData dynamically in this case?
I tried any and it worked but then it's useless to use TS at all,
I tried extends as well but i don't think i understand it well so that failed as well

Cannot change hidden column state from true to false on setState

I'm using devexpress React table and you can hide and show columns via state.
I would like to change the state for hidden from true to false but I get an Uncaught Invariant Violation error.
I've tried to use setState but doesn't work.
class ResultsTable extends Component {
constructor(props) {
super(props);
this.state = {
columns: [
{ name: 'agent', title: 'Agent' },
{ name: 'alertGroup', title: 'Alert Group', hidden:true },
{ name: 'manager', title: 'Manager', hidden:true }
],
};
}
componentDidMount() {
this.testAlert();
}
testAlert = () => {
if (this.props.alertgroupColumn()) {
this.setState({
columns: [{ name: 'alertGroup', title: 'Alert Group', hidden:false }]
})
}
}
Hidden should change from true to false.
I have another alternative to update your state
class ResultsTable extends Component {
constructor(props) {
super(props);
this.state = {
columns: [
{ name: 'agent', title: 'Agent' },
{ name: 'alertGroup', title: 'Alert Group', hidden:true },
{ name: 'manager', title: 'Manager', hidden:true }
],
};
}
componentDidMount() {
this.testAlert();
}
testAlert = () => {
if (this.props.alertgroupColumn()) {
//---- get the columns from state
let columns = JSON.parse(JSON.stringify(this.state.columns))
columns[1].hidden = false
this.setState({
columns:columns
})
this.setState({
columns: [{ name: 'alertGroup', title: 'Alert Group', hidden:false }]
})
}
}

Datatable did not show dynamic data which i fetch from database in react js

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

ionic 2 highchart not visible

I added highchart looking Page source but not visible on page
I followed this https://www.youtube.com/watch?v=FSg8n5_uaWs
how can ı solve this problem
my codes;
ts;
export class VerilerPage {
chartOptions : any;
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.chartOptions={
chart: {
type: 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}, {
name: 'John',
data: [5, 7, 3]
}]
}
}
html;
<chart options="chartOptions" type="chart" ></chart>
Since you are using angular 2/4, you have to enclose options with []
<chart [options]="chartOptions" type="chart" ></chart>

Uncaught TypeError: Cannot read property 'map' of undefined in react-redux-grid

I want to make a tree Grid by react-redux-grid. However I got the error: Uncaught TypeError: Cannot read property 'map' of undefined.
I had followed the instruction by https://github.com/bencripps/react-redux-grid/blob/master/docs/USING_TREE.md
Not sure what is going wrong, the codes is as below:
import { Grid } from 'react-redux-grid';
export const Tree = ({ store }) => {
const dataSource = {
data: [
{
id: 11,
parentId: 1,
name: 'Category 11',
editable: false,
leaf: true,
categoryCode: '12jf-3h3h-11'
}
],
partial: true
}
const data = {
root: {
id: -1,
parentId: null,
children: [
{
id: 1,
parentId: -1,
name: 'Category 1',
categoryCode: 'as-ffw-34neh-',
editable: true,
children: [
{
id: 12,
parentId: 1,
leaf: false // there are children for this record that haven't been fetched yet
// ... rest of data
},
{
id: 13,
parentId: 1
// ... rest of data
}
]
}
]
}
}
const treeConfig = {
stateKey: 'tree-grid-1',
gridType: 'tree', // either `tree` or `grid`,
showTreeRootNode: false, // dont display root node of tree
columns: [
{
dataIndex: 'category',
name: 'Category',
expandable: true // this will be the column that shows the nested hierarchy
},
{
dataIndex: 'categoryCode',
name: 'Category Code',
expandable: true // can be set on multiple columns
},
{
dataIndex: 'editable',
name: 'Editable',
expandable: false // will be displayed as flat data
}
],
data: data
dataSource: dataSource
};
return (
<Grid { ...treeConfig } />
);
}
//another page
let React = require('react');
import thunk from 'redux-thunk';
import Tree from '../Tree.jsx';
const reducers = {
//some reducers here
}
const store = createStore(reducer,applyMiddleware(thunk));
let gridPage = React.createClass({
render: function() {
return(
<Provider store={store}>
<Tree store={store} />
</Provider>
)
}
});

Resources