Example of Grid.js on React - javascript

Is there a React example using grid.js? having errors
import React from 'react';
import { Grid } from 'gridjs';
export const TableNew = () => {
const grid = new Grid({
columns: ['Weekly', 'Fortnightly', 'Monthly', 'Annually'],
data: () => [
['Pay', 0, 0, 0],
['Taxable Income', 0, 0, 0],
['Taxes', 0, 0, 0],
],
});
console.log('grid', grid);
return <div>{grid}</div>;
};
ERROR:
Error: Objects are not valid as a React child (found: object with keys {_config}). If you meant to render a collection of children, use an array instead.
in div (at TableNew.jsx:15)

There are no docs on this, but the way it works is that it needs a ref in order to render.
import React, { useEffect, useRef } from "react";
import { Grid } from "gridjs";
const TableNew = () => {
const wrapperRef = useRef(null);
useEffect(() => {
new Grid({
columns: ["Weekly", "Fortnightly", "Monthly", "Annually"],
data: () => [
["Pay", 0, 0, 0],
["Taxable Income", 0, 0, 0],
["Taxes", 0, 0, 0]
]
}).render(wrapperRef.current);
});
return <div ref={wrapperRef} />;
};
export default TableNew;
I created a sandbox with a working example.
https://codesandbox.io/embed/vigorous-hopper-n4xig?fontsize=14&hidenavigation=1&theme=dark
There is an open issue to add a React Wrapper https://github.com/grid-js/gridjs/issues/26 (I can guess, since the issue intention is not clearly described)

Here is an example with custom pagination, search, sorting and dynamic data from an api.
const ExampleComponent = () => {
const grid = new Grid({
search: {
enabled: true,
placeholder: 'Search...'
},
sort: true,
pagination: {
enabled: true,
limit: 5,
summary: false
},
columns: [
'Id',
'Tag',
'Name'
],
data: () => {
return api.movies.list({ locationId }).then(({ data }) => {
return data.results.map(movie => [movie.id, movie.tag, movie.name])
})
}
})
useEffect(() => {
grid.render(document.getElementById('wrapper'))
}, [locationId])
return (
<div id='wrapper' />
)
}

I just published the first version of the React component for Grid.js:
Install
npm install --save gridjs-react
Also, make sure you have Grid.js installed already as it's a peer dependency of gridjs-react:
npm install --save gridjs
Usage
<Grid
data={[
['John', 'john#example.com'],
['Mike', 'mike#gmail.com']
]}
columns={['Name', 'Email']}
search={true}
pagination={{
enabled: true,
limit: 1,
}}
/>
Links
Example: https://gridjs.io/docs/integrations/react
Repo: https://github.com/grid-js/gridjs-react
Edit on CodeSandbox: https://codesandbox.io/s/gridjs-react-ddy69

I am also using Grid.js in a react context. I found I had to install both Grid.js and the React integration:
npm install gridjs
npm install gridjs-react
and then change the import to this:
import {Grid} from "gridjs-react";
I am sure there is another way without the react wrapper but this is what did the trick for me.

Related

Vuejs implementing Vue-Select2 not showing on result

After installing vue3-select2-component with their document when i implementing that. it doesn't show in output on html but i have the html of that in source code
BTW: i'm using inertiajs on Laravel framework
install:
// npm install
npm install vue3-select2-component --save
Use as component:
import {createApp, h} from 'vue'
import BootstrapVue3 from 'bootstrap-vue-3'
import IconsPlugin from 'bootstrap-vue-3'
import {InertiaProgress} from "#inertiajs/progress";
import {createInertiaApp, Head} from '#inertiajs/inertia-vue3'
import {Link} from "#inertiajs/inertia-vue3"
///...
import Select2 from 'vue3-select2-component';
import {createStore} from "vuex"
///...
createInertiaApp({
resolve: async name => {
return (await import(`./pages/${name}`)).default;
},
setup({el, App, props, plugin}) {
createApp({render: () => h(App, props)})
.use(plugin)
.use(bootstrap)
.use(BootstrapVue3)
.use(IconsPlugin)
.use(VueSweetalert2)
.component('Link', Link)
.component('Select2', Select2)
.mount(el)
},
title: title => 'azizam - ' + title
}).then(r => {
});
vuejs page which i want to use into that:
<template>
<Select2 v-model="myValue" :options="myOptions"
:settings="{ settingOption: value, settingOption: value }"
#change="myChangeEvent($event)"
#select="mySelectEvent($event)" />
</template>
<script>
import menubar from "./menubar";
import emulator from "./emulator";
import {mapActions} from "vuex";
import notification from "../../../partials/notification";
export default {
name: "image",
data() {
return {
caption: '',
myValue: '',
myOptions: ['op1', 'op2', 'op3']
}
},
components: {
menubar,
emulator,
notification
},
methods: {
...mapActions([
'changeBreadcrumb'
]),
myChangeEvent(val){
console.log(val);
},
mySelectEvent({id, text}){
console.log({id, text})
}
},
mounted() {
const payload = {
title: 'محصولات',
subTitle: 'ایجاد محصول تک عکس در سامانه'
};
this.changeBreadcrumb(payload);
}
}
</script>
console log:
Warning - slinky.min.js is not loaded. application.js:336:21
[Vue warn]: A plugin must either be a function or an object with an "install" function. vendor.js:10544:17
[Vue warn]: Plugin has already been applied to target app. vendor.js:10544:17
Use of Mutation Events is deprecated. Use MutationObserver instead. content.js:19:11
Source map error: Error: request failed with status 404
Resource URL: http://127.0.0.1:8000/js/vendor.js?id=594b688c9609a79fb52afd907a69c736
Source Map URL: tooltip.js.map
in console as you can see i don't get any error for this component
html source code:
<select2 options="op1,op2,op3" settings="[object Object]"></select2>
and then webpack:
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
//.sass('resources/scss/app.scss','public/css')
.extract()
.vue({
version: 3,
options: {
compilerOptions: {
isCustomElement: (tag) => ['Select2'].includes(tag),
},
},
})
.postCss('resources/css/app.css', 'public/css', [
//
])
.version();
The problem is you've configured Vue to treat <Select2> as a custom element, so the actual component does not get rendered.
The fix is to remove that configuration:
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
//.sass('resources/scss/app.scss','public/css')
.extract()
.vue({
version: 3,
//options: {
// compilerOptions: {
// isCustomElement: (tag) => ['Select2'].includes(tag), ❌ remove this
// },
//},
})
.postCss('resources/css/app.css', 'public/css', [
//
])
.version();

ReferenceError: ResizeObserver is not defined:Gatsby with nivo

I use #nivo/pie with "gatsby": "^3.13.0".
But I got an error when I gatsby build.
WebpackError: ReferenceError: ResizeObserver is not defined
Nivo's version is "#nivo/pie": "^0.79.1".
I have no idea to solve it. I would be appreciate if you could give me some advice.
And here is the React code using nivo's pie chart.
PieChart.tsx
import React from 'react'
import { ResponsivePie } from '#nivo/pie'
const PieChart: React.FC = ({ data }) => {
return (
<>
<div>
<ResponsivePie
data={data}
margin={{ top: 30, right: 80, bottom: 70, left: 80 }}
borderColor={{
from: 'color',
modifiers: [
[
'darker',
0.2,
],
],
}}
arcLabelsTextColor={{
from: 'color',
modifiers: [
[
'darker',
2,
],
],
}}
fill={[
{
match: {
id: 'ruby',
},
id: 'dots',
},
]}
legends={[
{
anchor: 'bottom-right',
direction: 'column',
justify: false,
translateX: 0,
translateY: -1,
},
]}
/>
</div>
</>
)
}
export default PieChart
===================================================================
I could fix it after I updated gatsby-node.js. But I got another error WebpackError: Minified React error #130;. And I could fix it by this final code. There's no build error.
PieChart.tsx
import React from 'react'
import { ResponsivePie } from '#nivo/pie'
const PieChart: React.FC = ({ data }) => {
return (
<>
{typeof window !== 'undefined' && ResponsivePie &&
<ResponsivePie
data={data}
...
/>}
</>
)
}
export default PieChart
Thank you.
Try using a null loader on Gatsby's SSR. In your gatsby-node.js:
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /#nivo\/pie/,
use: loaders.null(),
},
],
},
})
}
}
Normally this kind of issue (gatsby develop OK vs gatsby build KO) are related to webpack's bundling on the server (Server-Side Rendering), especially when dealing with third-party dependencies that interact with the window or other global objects (such as document) like chart modules do. This happens because when you run gatsby build your code is interpreted by the Node server, where there's no window available yet. On the other hand, gatsby develop is interpreted by the browser, where there is.
With this approach, you are adding a dummy loader (null) to webpacks to load the dependency on the client-side, where the window is available.
Keep in mind that test: /#nivo\/pie/ is a regular expression (that's why is between slashes, /) that tests the node_modules folder so ensure that /#nivo\/pie/ is a valid path.

How to generate a QR Code with multiple values like name, email, etc in React Native

I am able to create QR Code with single value by using react-native-qrcode-svg package. But not able to add multiple values like name,email, etc.
I have tried these :
Packages:
npm install react-native-svg --save
react-native link react-native-svg
npm install react-native-qrcode-svg --save
Code for generating QR Code using single value.
import * as React from 'react';
import QRCode from 'react-native-qrcode-svg';
export default class App extends React.Component {
render() {
return (
<QRCode
value="Here I want to add name, email,etc"
/>
);
};
}
I want to generate something like this
You can use rn-qr-generator module to create QRCode Image with a given string.
To generate a QRCode image with an object just do something like this
import RNQRGenerator from 'rn-qr-generator';
RNQRGenerator.generate({
value: JSON.stringify({ email: 'some.email.com', name: 'Name' })
height: 100,
width: 100,
base64: false, // default 'false'
backgroundColor: 'black', // default 'white'
color: 'white', // default 'black'
})
.then(response => {
const { uri, width, height, base64 } = response;
this.setState({ imageUri: uri });
})
.catch(error => console.log('Cannot create QR code', error));
According to the documentation here, https://www.npmjs.com/package/react-native-qrcode-svg, the value can be an array:
String Value of the QR code. Can also accept an array of segments as defined in Manual mode. Ex. [{ data: 'ABCDEFG', mode: 'alphanumeric' }, { data: '0123456', mode: 'numeric' }, { data: [253,254,255], mode: 'byte' }]
Hence the code should be
import * as React from 'react';
import QRCode from 'react-native-qrcode-svg';
export default class App extends React.Component {
render() {
return (
<QRCode
value="[{ name: 'my name'},{ email: 'email#email.com' }]"
/>
);
};
}
I never used react, but shouldn't be something like
value={`"name={name},email={email},phone={phone}"`}
enough to compute the value?
<QRCode
value={`${email},${mdp}`}
/>
if you want to read the data:
data=result.split(",")

How to use vanilla javascript inside Reactjs component?

I am using chartist.js and I am using the chartist within reactjs component.
I am referring this http://gionkunz.github.io/chartist-js/examples.html#simple-pie-chart
chartist.js:
var Chartist = {
version:'0.9.5'
}
(function (window, document, Chartist) {
var options = {
labelInterpolationFnc: function(value) {
return value[0]
}
};
var responsiveOptions = [
['screen and (min-width: 640px)', {
chartPadding: 30,
labelOffset: 100,
labelDirection: 'explode',
labelInterpolationFnc: function(value) {
return value;
}
}],
['screen and (min-width: 1024px)', {
labelOffset: 80,
chartPadding: 20
}]
];
})();
Reactjs component:
import React, { Component } from 'react';
var data = {
labels: ['Bananas', 'Apples', 'Grapes'],
series: [20, 15, 40]
};
showPieChart(data){
new Chartist.Pie('.ct-chart', data, options, responsiveOptions);
}
class Chart extends Component {
render(){
return(
<div>
<div className="center">
{showPieChart}
</div>
</div>
)}
}
export default Chart;
Nothing is displayed on web page. How can I access vanilla javascript inside react component.
Your question is a little bit misleading, and can be interpreted in two ways.
#1. If you're asking how to integrate Chartist library with React, here's how you can do it:
There's a wrapper library, that already did it for us: https://www.npmjs.com/package/react-chartist
You can use it as follow (example taken from their repo):
import React from 'react';
import ReactDOM from 'react-dom';
import ChartistGraph from 'react-chartist';
class Pie extends React.Component {
render() {
var data = {
labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'],
series: [
[1, 2, 4, 8, 6, -2, -1, -4, -6, -2]
]
};
var options = {
high: 10,
low: -10,
axisX: {
labelInterpolationFnc: function(value, index) {
return index % 2 === 0 ? value : null;
}
}
};
var type = 'Bar'
return (
<div>
<ChartistGraph data={data} options={options} type={type} />
</div>
)
}
}
ReactDOM.render(<Pie />, document.body)
#2. If you generally asking how to integrate other libraries into React, then I recommend you to check the official React docs, because there's a really good tutorial about the topic - Integrating with Other Libraries
So, if you don't want to use the wrapper library (react-chartist), then you can check its main component too. It's a great starting point (that follows React recommendations) to understand how to create your own wrapper: https://github.com/fraserxu/react-chartist/blob/master/index.js

React "document not defined" when including script

I'm using ReactJS with Routing, ES6, Babel and ESLint.
On click I want to add a CSS class using the classnames library, but I can't even use the document.querySelector. My whole application crashes and prints the error: ReferenceError: document is not defined
import React from 'react';
import { connect } from 'react-redux';
export default class Nav extends React.Component {
constructor(props) {
super(props);
const sideNavToggleButton = document.querySelector('.js-toggle-menu');
sideNavToggleButton.addEventListener('click', () => {
console.info('clicked');
});
}
render() {
return (
<header>
<button role="tab" className="header__menu js-toggle-menu">Toggle nav menu</button>
<h1 className="header__title">App Shell</h1>
</header>
);
}
}
After some research I found out it might be my ESLint settings missing some environments, but after adding browser the application is still breaking.
module.exports = {
'parser': 'babel-eslint',
'plugins': [
'react'
],
'rules': {
'indent': [2, 'tab'],
'max-len': 0,
'no-console': [2, { allow: ['info', 'error']}],
'no-param-reassign': 0,
'react/jsx-indent': [2, 'tab'],
'react/jsx-indent-props': [2, 'tab'],
'no-new': 0
},
'env': {
'browser': true,
'node': true
}
};
Any idea?
You have to move this part of your code to the method componentDidMount()
const sideNavToggleButton = document.querySelector('.js-toggle-menu');
sideNavToggleButton.addEventListener('click', () => {
console.info('clicked');
});
Because componentDidMount() is the method that is called after the first rendering here. After rendering you can do any dom manipulation.

Categories