'JsonTable' is not defined react/jsx-no-undef - javascript

I'm trying to get an Json value into the json table in react but it is throwing an error "'JsonTable' is not defined react/jsx-no-undef".
What should i do? Is there Some file i need to import.
import React, { Component } from 'react';
import {Link} from 'react-router-dom';
export default class SearchHistory extends Component {
constructor()
{
super();
this.state={data:null};
}
componentDidMount () {
this.data().then(data => {
const self=this;
this.setState({data:data});
});
}
columns() {
return[
{key:'name',label:'Name'},
{key:'age',label:'Age'},
{key:'color',label:'Color',cell:(obj,key) => {
return <span>{obj[key]} </span>;
}}
];
}
data() {
return new Promise((resolve,reject)=> {
resolve([
{name:'sssss',age:20,color:'red'}
]);
});
}
render() {
<JsonTable rows={this.state.data} columns={this.columns()} />
return (
<div>Loading.... </div>
)
}
}
Thank you

Sorry for my late answer:
I tried the JsonTable, but i think it uses the deprecated "React.createClass" in the library so it doesn't work in React 15...
here is a working samle in react 0.14.8:
hope this helps :)
/*
Simplest example for react-json-table.
To see the customization options visit
https://github.com/arqex/react-json-table
*/
var items = [
{ name: 'Louise', age: 27, color: 'red' },
{ name: 'Margaret', age: 15, color: 'blue'},
{ name: 'Lisa', age:34, color: 'yellow'}
];
React.render(
<JsonTable rows={ items } />,
document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<script src="https://rawgit.com/arqex/react-json-table/master/build/react-json-table.min.js"></script>
I think you need to import react-json-table from : https://github.com/arqex/react-json-table
because react doesn't know JsonTable.
-> to do so:
add react-json-table to your project:
npm install react-json-table --save
then simply add at the top of your file:
import {JsonTable} from 'react-json-table';

Related

Error 'Do not use findDOMNode'; how to fix the code so it doesn't complain?

I have a javascript class that is in my react project.
Basically, i wanted to add a sunburst pie chart to my UI. So I put the code for it in my react project. At compile time (i.e. when i run npm start) I get the error
error Do not use findDOMNode react/no-find-dom-node
I read online but I still don't completely understand this error (or what findDOMNode does, for that matter).
I simply need to fix the code for findDOMNode to whatever it needs to be, as for now I am just disabling the rule.
import React from "react";
import ReactDOM from "react-dom";
import Sunburst from "sunburst-chart";
/* eslint-disable react/no-find-dom-node */
/* eslint-disable no-console */
const data = {
name: "main",
color: "magenta",
children: [
{
name: "a",
color: "yellow",
size: 1
},
{
name: "b",
color: "red",
children: [
{
name: "ba",
color: "orange",
size: 1
},
{
name: "bb",
color: "blue",
children: [
{
name: "bba",
color: "green",
size: 1
},
{
name: "bbb",
color: "pink",
size: 1
}
]
}
]
}
]
};
class SunburstChart extends React.Component {
constructor() {
super();
this.state = {
myChart: Sunburst().data(data)
};
}
componentDidMount() {
// set el height and width etc.
this.state.myChart(ReactDOM.findDOMNode(this));
}
onSelect(event) {
console.log(event);
}
render() {
return <div id="chart" />;
}
}
export default SunburstChart;
Facebook will eventually deprecate findDOMNode as it blocks certain improvements in React in the future.
It is recommended to use callback refs instead. See Dan Abramov comments and examples here:
https://github.com/jsx-eslint/eslint-plugin-react/issues/678#issue-165177220
source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-find-dom-node.md
I was able to work it out after reviewing the github links
componentDidMount() {
// set el height and width etc.
this.state.myChart(this.node);
}
onSelect(event) {
console.log(event);
}
render() {
return <div id="chart" ref={node => this.node = node}/>;
}

How to use Vue 3 Meta with Vue.js 3?

It seems that Vue Meta has been upgraded to handle Vue.js 3 with a new npm package called vue-3-meta
Before Vue.js 3, it was easy to use vue-meta by adding it to the Vue instance:
import Vue from 'vue'
import VueMeta from 'vue-meta'
Vue.use(VueMeta, {
// optional pluginOptions
refreshOnceOnNavigation: true
})
However in Vue.js 3, there is no Vue instance; and instead you create the app by running createApp like such:
const app = createApp(App);
const router = createVueRouter();
app.use(router);
// need to make app use Vue-Meta here
I cannot find any documentation for vue-3-meta. import VueMeta from 'vue-meta' no longer works.
How do I import the vue-3-meta plugin properly and use it with app like in prior versions?
Disclaimer: vue-meta v3 is still in alpha!
This was the minimal implementation I needed to get started:
Update vue-meta to v3 (in package.json)
- "vue-meta": "^2.4.0",
+ "vue-meta": "^3.0.0-alpha.7",
...or with yarn:
yarn add vue-meta#alpha
Add metaManager to Vue app
import { createMetaManager } from 'vue-meta'
const app = createApp(App)
.use(router)
.use(store)
.use(createMetaManager()) // add this line
await router.isReady()
app.mount('#app')
Add <metainfo> to App.vue <template> (this is also where I set a "title template")
<template>
<metainfo>
<template v-slot:title="{ content }">{{ content ? `${content} | SITE_NAME` : `SITE_NAME` }}</template>
</metainfo>
<header />
<router-view />
<footer />
</template>
Set default meta in App.vue <script>
Vue 3 vanilla:
import { useMeta } from 'vue-meta'
export default {
setup () {
useMeta({
title: '',
htmlAttrs: { lang: 'en', amp: true }
})
}
}
or with vue-class-component:
import { setup, Vue } from 'vue-class-component'
import { useMeta } from 'vue-meta'
export default class App extends Vue {
meta = setup(() => useMeta({
title: '',
htmlAttrs: { lang: 'en', amp: true }
})
}
Override meta in each component
Vue 3 vanilla:
import { useMeta } from 'vue-meta'
export default {
setup () {
useMeta({ title: 'Some Page' })
}
}
or with vue-class-component:
import { computed } from '#vue/runtime-core'
import { setup, Vue } from 'vue-class-component'
import { useMeta } from 'vue-meta'
export default class SomePage extends Vue {
meta = setup(() => useMeta(
computed(() => ({ title: this.something?.field ?? 'Default' })))
)
}
See also:
"Quick Usage" (vue-meta next branch)
Vue Router Example (vue-meta next branch)
In addition to the previous answers, I also needed to add a transpileDependency in my vue.config.js, as I was using vue-cli:
module.exports = {
transpileDependencies: ['vue-meta']
}
Else, I would get the error:
error in ./node_modules/vue-meta/dist/vue-meta.esm-browser.min.js
Module parse failed: Unexpected token (8:7170)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
Thanks to this thread for pointing me to this: https://stackoverflow.com/a/65844988/3433137
metaManager is a MetaManager instance created from createMetaManager() of vue-meta.
Based on the Vue 3 + Vue Router example for vue-meta, here's an example usage:
import { createApp } from 'vue'
import { createMetaManager, defaultConfig, resolveOption, useMeta } from 'vue-meta'
const decisionMaker5000000 = resolveOption((prevValue, context) => {
const { uid = 0 } = context.vm || {}
if (!prevValue || prevValue < uid) {
return uid
}
})
const metaManager = createMetaManager({
...defaultConfig,
esi: {
group: true,
namespaced: true,
attributes: ['src', 'test', 'text']
}
}, decisionMaker5000000)
useMeta(
{
og: {
something: 'test'
}
},
metaManager
)
createApp(App).use(metaManager).mount('#app')

React-Codemirror match-highlighter addon not highlighting the text

I am using react-codemirror and want to highlight the text 'Hello' in the Codemirror but the match-highlighter addon is not highlighting the same. Below is the code for the same.
import React, { Component } from 'react';
import { render } from 'react-dom';
import CodeMirror from 'react-codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/addon/search/match-highlighter';
import 'codemirror/mode/javascript/javascript';
class App extends Component {
constructor() {
super();
this.state = {
name: 'CodeMirror',
code: '//Test Codemirror'
};
}
updateCode(newCode) {
this.setState({
code: newCode,
});
}
render() {
let options = {
lineNumbers: true,
mode: 'javascript',
highlightSelectionMatches: {
minChars: 2,
showToken: /Hello/,
style:'matchhighlight'
},
styleActiveLine: true,
styleActiveSelected: true,
};
return (
<div>
<CodeMirror value={this.state.code} onChange={this.updateCode.bind(this)} options={options}/>
</div>
);
}
}
render(<App />, document.getElementById('root'));
Current output is in the screenshot below and the word is not highlighted.
I found a solution for this issue. Inorder to enable the highlighting one need to add a css corresponding to the style property. I added the below code in css file and it started working
.cm-matchhighlight {
background: red !important
}
Now it highlights the token properly

What does h is not defined mean?

I've used vue create to setup a new Vue project, and have installed Storybook - all working correctly.
I have then installed storybook-addon-designs and followed the readme on adding to my story, but it gives me the following error in my console: h is not defined.
Here's my files:
stories/2-PageTitle.stories.js:
import { withDesign } from 'storybook-addon-designs'
import {Button} from '../src/components/Button'
export default {
title: 'My stories',
component: Button,
decorators: [withDesign]
}
export const myStory = () => <Button>Hello, World!</Button>
myStory.story = {
name: 'My awesome story',
parameters: {
design: {
type: 'figma',
url: 'https://www.figma.com/file/LKQ4FJ4bTnCSjedbRpk931/Sample-File'
}
}
}
babel.config.js:
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset'
]
}
.storybook/main.js:
module.exports = {
stories: ['../stories/**/*.stories.js'],
addons: ['storybook-addon-designs']
};
src/components/Button.vue:
<template>
<button>
{{ label }}
</button>
</template>
<script>
export default {
name: 'Button',
props: {
label: String
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
button {
background: red;
}
</style>
Can anyone see what I'm doing wrong here?
Full code here (I'd of done a Sandbox but because it uses Storybook this seems like a better way?): https://github.com/A7DC/storybookvueaddonstest
The author of storybook-addon-designs suggests the following:
You have to replace the export
const myStory = () => <Button>Hello, World!</Button>
You need to change this line (React story) to Vue's one. For example,
export const myStory = () => ({
components: { Button },
template: '<Button>Hello, World!</Button>'
})
Updated answer -
import { withDesign } from "storybook-addon-designs";
import Button from "../src/components/Button";
export default {
title: "My Stories",
decorators: [withDesign],
};
export const myStory = () => ({
components: { Button },
template: "<Button> Hello, World!</Button >",
});
myStory.story = {
name: "My awesome story",
parameters: {
design: {
type: "figma",
url: "https://www.figma.com/file/LKQ4FJ4bTnCSjedbRpk931/Sample-File",
},
},
};

React lightgallery.js integration without JQuery?

I've been searching for a proper guidance for integrating lightgallery.js library into my application, but after several hours I did not find any solutions. Since I'm using React, I don't want to mix it with JQuery.
I've stumbled across many similar questions like this one, but since all of them are using JQuery, I can't use their solutions.
Also, I've found react-lightgallery package (React wrapper for lightgallery.js), but it does not include video support yet.
In the lightgallery.js documentation, there is the installation guidance. After completing all of the steps, importing lightgallery.js and trying to print it (as suggested here by the library owner), empty object is being shown.
What would be the best solution for this? Are there any good alternatives?
Thanks!
I have handled it this way. May be it's not complete and the best practice, but it gives you a general view to how to handle it
import React, { PureComponent } from "react";
import Gallery from "lightgallery.js";
import "lightgallery.js/dist/css/lightgallery.min.css";
class _Gallery extends PureComponent {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
let self = this;
this.gallery = document.getElementById("lightgallery");
lightGallery(this.gallery, {
dynamic: true,
dynamicEl: [
{
src:
"1.jpg",
thumb: "1.jpg",
subHtml:
"<h4>Fading Light</h4><p>Classic view</p>"
},
{
src:
"2.jpg",
thumb: "2.jpg",
subHtml:
"<h4>Bowness Bay</h4><p>A beautiful Sunrise</p>"
},
{
src:
"3.jpg",
thumb: "3.jpg",
subHtml: "<h4>Coniston Calmness</h4><p>Beautiful morning</p>"
}
]
});
this.gallery.addEventListener("onCloseAfter", function(event) {
window.lgData[self.gallery.getAttribute("lg-uid")].destroy(true);
self.props.onCloseGallery();
});
}
render() {
return <div id="lightgallery" />;
}
}
export default _Gallery;
Here is a working example with cloudinary at Cloudinary LightGallery
The code for the Cloundinary LightGallery React Component using Styled Components and styled css grid is below.
The Code for the upload component is in my GitHub Repo at.
UploadWidget
/* eslint-disable indent */
import React, { Component, Fragment } from 'react'
import { LightgalleryProvider, LightgalleryItem } from 'react-lightgallery'
import axios from 'axios'
import styled from 'styled-components'
import { CloudinaryContext, Transformation, Image } from 'cloudinary-react'
import { Grid, Cell } from 'styled-css-grid'
import { media } from '../../utils/mediaQuery'
import 'lightgallery.js/dist/css/lightgallery.css'
import 'lg-autoplay.js'
const SectionTitle = styled.h3`
font-size: 1em;
margin: 0.67em 0;
${media.xs`
font-size: .85em;
`}
`
class Gallery extends Component {
constructor (props) {
super(props)
this.link = React.createRef()
this.state = {
gallery: [],
isOpen: false,
link: this.href,
}
}
componentDidMount () {
// Request for images tagged cats
axios.get('https://res.cloudinary.com/mansbooks/image/list/v1557911334/cats.json')
.then(res => {
console.log(res.data.resources)
this.setState({ gallery: res.data.resources })
})
}
onLink (event) {
this.setState({ link: this.href =
`https://res.cloudinary.com/mansbooks/image/upload/${data.public_id}.jpg` })
}
uploadWidget () {
let _this = this
cloudinary.openUploadWidget({ cloud_name: 'mansbooks', upload_preset: 'photos-
preset', tags: ['cats'], sources: ['local', 'url', 'camera', 'image_search',
'facebook', 'dropbox', 'instagram'], dropboxAppKey: 'Your API Key', googleApiKey:
'Your API Key' },
function (error, result) {
// Update gallery state with newly uploaded image
_this.setState({ gallery: _this.state.gallery.concat(result) })
})
}
render () {
return (
<div>
<Fragment>
<SectionTitle>Gallery by Cloudinary</SectionTitle>
<div>
<CloudinaryContext cloudName='mansbooks'>
<Grid columns='repeat(auto-fit,minmax(260px,1fr))' id='hash'>
<LightgalleryProvider>
{
this.state.gallery.map(data => {
return (
<Cell key={data.public_id}>
<LightgalleryItem group='group1' src={`https://res.cloudinary.com/mansbooks/image/upload/${data.public_id}.jpg`} data-sub-html={'data.public_id'}>
<Image publicId={data.public_id} onClick={() => this.setState({ isOpen: true })}>
<Transformation
crop='scale'
width='250'
height='170'
radius='6'
dpr='auto'
fetchFormat='auto'
responsive_placeholder='blank'
/>
</Image>
</LightgalleryItem>
</Cell>
)
})
}
</LightgalleryProvider>
</Grid>
</CloudinaryContext>
</div>
</Fragment>
</div>
)
}
}
export default Gallery

Categories