I'm trying to create a dynamic column in react.js any body have an idea? I've already done with the static column but I want to make them dynamic have a look on my code and please give me suggestion.
import React from 'react';
import ReactDataGrid from 'react-data-grid';
class Example extends React.Component {
constructor(props, context) {
super(props, context);
this.createRows();
this._columns = [
{ key: 'id', name: 'ID' },
{ key: 'title', name: 'Title' },
{ key: 'count', name: 'Count' } ];
this.state = null;
}
createRows = () => {
let rows = [];
for (let i = 1; i < 5; i++) {
rows.push({
id: i,
title: 'Title ' + i,
count: i * 1000
});
}
this._rows = rows;
};
rowGetter = (i) => {
return this._rows[i];
};
render() {
return (
<ReactDataGrid
columns={this._columns}
rowGetter={this.rowGetter}
rowsCount={this._rows.length}
minHeight={200} />);
}
}
export default Example;
You can try this function to create dynamic column key and name
createColumns = async (data) => {
let columns = [], keys = [];
if (data)
keys = Object.keys(data);
for (let i = 0; i < keys.length; i++) {
columns.push({key: Object.keys(data)[i], name: Object.keys(data)[i]});
}
await this.setState({columns});
};
Related
I need to generate an array of 10 items and this is the code I have to use.
for (let i = 0; i < 10; i++) {
vehicles.push({
manufacturer: faker.vehicle.manufacturer(),
model: faker.vehicle.model(),
type: faker.vehicle.type(),
fuel: faker.vehicle.fuel(),
vin: faker.vehicle.vin(),
color: faker.vehicle.color()
})
}
My question is how do I use it? So far I have this:
import React from 'react';
import Stack from 'react-bootstrap/Stack'
import VehicleActions from './VehicleActions';
import VehicleList from './VehicleList';
import Vehicle from './Vehicle';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { vehicles: [] };
this.onNewContact = this.onNewContact.bind(this);
this.handleContactSelected = this.handleContactSelected.bind(this)
this.handleDeleteContact = this.handleDeleteContact.bind(this)
}
onNewContact(vehicle) {
this.setState((state) => {
return {
vehicles: state.vehicles.concat(vehicle)
}
})
}
handleContactSelected(manufacturer) {
this.setState((state) => {
return {
selected: manufacturer
}
})
}
handleDeleteContact(manufacturer) {
this.setState((state) => {
return {
vehicles: state.vehicles.filter((vehicle) => vehicle.manufacturer !== manufacturer),
selected: null
}
})
}
handleGenerateVehicle() {
this.props.onNewContact(this.generateContact())
}
render() {
return (
<Stack gap={3} className="col-md-10 mx-auto">
<VehicleActions onNewContact={this.onNewContact}
selectedContact={this.state.selected} />
<Vehicle />
<VehicleList vehicles={this.state.vehicles}
onContactSelected = {this.handleContactSelected}/>
</Stack>
)
}
}
export default App
I'm using the "npm install react-bootstrap bootstrap #faker-js/faker" to generate the random text, I have tested it in the alert or console log and it works, but I have no clue where to insert it so the 10 values are shown in a column.
If you want to hardcode the list of vehicles (I assume that is what you are supposed to do), just put the code in the constructor:
class App extends React.Component {
constructor(props) {
super(props);
let vehicles = [];
for (let i = 0; i < 10; i++) {
vehicles.push({
manufacturer: faker.vehicle.manufacturer(),
model: faker.vehicle.model(),
type: faker.vehicle.type(),
fuel: faker.vehicle.fuel(),
vin: faker.vehicle.vin(),
color: faker.vehicle.color()
})
}
this.state = { vehicles };
this.onNewContact = this.onNewContact.bind(this);
this.handleContactSelected = this.handleContactSelected.bind(this)
this.handleDeleteContact = this.handleDeleteContact.bind(this)
}
// ...
}
I cannot get my data to populate my line chart.
The data from the API call comes back fine but when I try to pass that data into the chart it is of length 0. So I assume there is some issue with the response got being called at the right time? But I have tried so many times to sort this and nothing ever works?
import React from 'react';
import NVD3Chart from 'react-nvd3';
import SamplePage from './SamplePage';
function getData(){
const alpha = require('account')({ key: 'xxxxxxxxxxxx' });
var array = [];
alpha.data.intraday(`msft`).then((data) => {
const polished = alpha.util.polish(data);
{Object.keys(polished.data).map((key) => (
array.push(polished.data[key].open)
))}
});
return array;
}
function getDatum() {
let dataArray = getData();
let newArray = [];
for (let index = 0; index < dataArray.length; index++) {
const element = dataArray[index];
newArray.push({
'x': index,
'y': parseFloat(element)
})
}
return [
{
data: newArray,
key: 'OpenPrice',
color: '#A389D4'
}
];
}
class LineChart extends React.Component {
constructor(props) {
super(props);
this.state = {
DataisLoaded: false,
data:[]
};
}
componentDidMount() {
this.state.data = getDatum();
this.setState(
{
DataisLoaded: true,
data: this.state.data
}
)
}
render() {
const { DataisLoaded } = this.state;
if (!DataisLoaded) return <div>
<h1> Please wait.... </h1> </div>;
return (
<div>
{
React.createElement(NVD3Chart, {
xAxis: {
tickFormat: function(d){ return d; },
axisLabel: 'Time (ms)'
},
yAxis: {
axisLabel: 'Voltage (v)',
tickFormat: function(d) {return parseFloat(d).toFixed(2); }
},
type:'lineChart',
datum: this.state.data,
x: 'x',
y: 'y',
height: 300,
renderEnd: function(){
console.log('renderEnd');
}
})
}
</div>
)
}
}
export default LineChart;
Im wondering how I can call a method from outside of a React Functional Component. I wrote the function GetUsedLockers() which gets all the used lockers and returns amount. Now I want to call this function from another another component (OrgLocker.tsx) and display the data from the getUsedLockers() function there.
OrgLockerTables.tsx
const OrgLockerTables: React.FC = () => {
const lockerCall = 'lockers';
const [lockerData, setLockerData] = useState({
id: 0,
guid: "",
is_currently_claimable: false
}[""]);
useEffect(() => {
componentConsole().then((res) => {
setLockerData(res);
})
// eslint-disable-next-line
}, []);
if (!lockerData) return (<div>Loading...</div>);
//function to get all used lockers
function getUsedLockers() {
let amount = 0;
for (let i = 0; i < lockerData.length; i++) {
if (!lockerData.is_currently_claimable) {
amount++;
}
}
console.log('log from getusedlockers, amount: ', amount)
return (amount)
}
// function to get JSON data from the API
function componentConsole(): Promise<any> {
return new Promise<any>((resolve, reject) => {
http.getRequest('/' + lockerCall).then((res) => {
let data = res.data.data;
console.log('data:', data);
resolve(res.data.data);
}).catch((error) => {
console.log(error);
reject();
});
})
}
}
OrgLocker.tsx
import OrgLockerTables from '../tables/orgLockerTables';
const OrgLockers: React.FC = () => {
let lockerTable = new OrgLockerTables();
return (
<div className="main-div-org">
<p>Used</p>
<p>{lockerTable.getUsedLockers()}</p>
</div>
);
}
export default OrgLockers;
When trying to make a call to OrgLockerTables and storing it in the lockerTable let it gives the following error:
Expected 1-2 arguments, but got 0.ts(2554)
Any help would be greatly appreciated!
I've restructured everything making it more understandable, I hope you don't mind according to what I think you want the comment above.
locker-model.ts - The type for the particular data being called back is found
export type Locker = {
id: number;
guid: string;
isCurrentlyClaimable: boolean;
}
locker-business.ts - Where all the business logic is carried out, from the call for data to the calculation based on it
import { Locker } from "./locker-models";
const lockerCall = 'lockers';
const mockedData: Locker[] = [{
id: 0,
guid: "sample",
isCurrentlyClaimable: false,
},
{
id: 1,
guid: "sample2",
isCurrentlyClaimable: true,
},
{
id: 2,
guid: "sample3",
isCurrentlyClaimable: true,
}]
// Mocked function from your backend (componentConsole where you use lockerCall variable)
export const getLockersData = (): Promise<Locker[]> => Promise.resolve(mockedData);
export const getAmount = (lockers: Locker[]): number => {
let amount = 0;
!!lockers ?
lockers.filter(({isCurrentlyClaimable}) => { if(isCurrentlyClaimable) amount++ })
: 0;
return amount;
};
index.tsx - Here are both components that make the call to get the data and render the result you're looking for
import React, { Component } from 'react';
import { Locker } from './locker-models';
import { getLockersData, getAmount } from './locker-business';
import './style.css';
type OrgLockersProps = {
amount: number;
}
const OrgLockers: React.FC<OrgLockersProps> = ({ amount }) => {
return (
<div className="main-div-org">
<p>Lockers used:</p>
<p>{amount}</p>
</div>
);
}
type OrgLockerTableProps = {};
const OrgLockerTable : React.FC<OrgLockerTableProps> = props => {
const [lockerData, setLockerData] = React.useState<Locker[]>([]);
React.useEffect(() => {
getLockersData().then(response => setLockerData(response));
}, []);
const amount = getAmount(lockerData);
return (
<div>
<OrgLockers amount={amount} />
</div>
);
};
You can see the example here
You can create new .js file like Helpers.js and define export function with parameter it like that
export function getUsedLockers(lockerData) {
let amount = 0;
//Check your loop it can be like that
for (let i = 0; i < lockerData.length; i++) {
if (!lockerData[i].is_currently_claimable) {
amount++;
}
}
console.log('log from getusedlockers, amount: ', amount)
return (amount)
}
Then import it where do you want to use.
import {getUsedLockers} from "../Helpers";
And use it like that:
const amount = getUsedLockers(data);
I am writing some react frontend application. I want to pass just header from table object to my function. I am using react-redux and redux-saga
In the reducer.js I am creating this object table, it has 2 arrays inside.
Code starts in render() and then calls Table which calls TableRows and TableHead
Later I pass table to TableHead as data variable (to avoid using as html table). But when I do data.header or data["header"] in TableHead method, the array I receive has 0 length and it is empty.
How can I get this array? I have to use map or some built-in functionality?
// Picture is created from this snippet
//AuthorsTable.js
const TableHead = ({data}) => {
console.log("Making header")
// var header = data.header
console.log(data)
console.log(data["header"])
console.log(data.header)
//reducer.js
...
case 'UPDATE_TABLE':
// console.log("Updating", action.author_obj.id)
var proto_obj = action.value;
// console.log("value:", obj)
var words = Object.keys(proto_obj).map(function (key) {
return {id: key, label: proto_obj[key]};
});
newState.table.header = [...newState.table.header, action.author_obj]
newState.table.content = [...newState.table.content, [words]]
return newState
...
//AuthorsTable.js
const TableHead = ({data}) => {
console.log("Making header")
// var header = data.header
console.log(data)
console.log(data["header"])
console.log(data.header)
var header = Object.keys(data.header).map(function (key) {
return {id: key, label: data[key]};
});
console.log(header)
const TableRows = ({data}) => {
return (<tbody><tr><td>content</td></tr></tbody>)
// for (let i = 0; i < 3; i++) {
// let children = []
// //Inner loop to create children
// for (let j = 0; j < 5; j++) {
// children.push(<td>{`Column ${j + 1}`}</td>)
// }
// return children
// }
}
const Table = ({data}) => {return(
<table>
<TableHead data={data} />
<TableRows data={data} />
</table>
)}
class AuthorsTable extends Component {
constructor(props) {
super(props);
}
render() {
const state = this.state;
// console.log(this.props.table)
return (
<Table data={this.props.table} />
// "Hello"
)
}
}
const mapStateToProps = state => {
return {
// authors: state.authors,
selectedItems: state.selectedItems,
table: state.table,
};
};
export default connect(
mapStateToProps,
)(AuthorsTable);
This was not working.
newState.table.header = [...newState.table.header, action.author_obj]
newState.table.content = [...newState.table.content, [words]]
Solution:
Creating new object, and then replacing it in state.
...
// reducer.js
// working code
const newState = { ... state };
var new_table = {
header: [...newState.table.header, action.author_obj],
content: [...newState.table.content, [words]],
}
newState.table = new_table
return newState
somebody knowing JS better can explain this further
I am trying to map a dynamic array with an address and a string from solidity to react to look like a table or print out the address and string in a list but I can't manage to separate those 2 values.
class App extends Component {
constructor(props) {
super(props);
this.state = {
Data: []
};
}
GetData = async () => {
const { accounts, contract, count, Data } = this.state;
const data = [];
for (var i = 0; i < count.length; i++) {
const dataa = await contract.methods.getInfo(i).call();
data.push(dataa);
}
console.log(data);
this.setState({ Data: JSON.stringify(data) });
};
render() {
return (
<>
<button onClick={this.GetData}>Show</button>
<h1>{this.state.Data}</h1>
</>
);
}
}
export default App;
This is what my console prints and it shows the data in the website as 0:<address> 1: <string>
(2) [Result, Result]
0: Result
0: "0x7e3ce0fc8F95Bb83A4f5131912DacBFf11B9d4f8"
1: "{test1}"
__proto__: Object
1: Result {0: "0x514bdB4F417926027dDa4f0ccb2a6674a31D4BcB", 1: "{test2"}
length: 2
__proto__: Array(0)
Try separating before you stringify. Actually, why do you stringify at all?
This should do:
class App extends Component {
constructor(props) {
super(props);
this.state = {
Data: []
};
}
GetData = async () => {
const { accounts, contract, count, Data } = this.state;
const data = [];
for (var i = 0; i < count.length; i++) {
const dataa = await contract.methods.getInfo(i).call();
data.push(dataa);
}
console.log(data);
this.setState({ Data: data });
};
render() {
return (
<>
<button onClick={this.GetData}>Show</button>
{ this.state.Data.map(item => <h1>{item.toString()}</h1>) }
</>
);
}
}
export default App;