React lightgallery.js integration without JQuery? - javascript

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

Related

Writing documentation for plain JS class in storybook

I have just started using Storybook for a UI component lib I am working on. I wanted to extract JSDoc written for JS class methods and properties into Storybook and create a Doc.
Storybook does support creating doc for React components by reading its propTypes. Is there addon or someway to do the same for a JS class.
I am using the latest storybook 6.
Thanks in advance
You can do it like a normal component:
form-validators.stories.ts
import { FormValidators } from './path';
export default {
title: 'Components/Form Validators',
component: FormValidators,
parameters: {
previewTabs: { canvas: { hidden: true } },
docsOnly: true,
},
} as Meta;
export const Default: Story = () => ({
template: '<div>Test</div>',
});
Or I prefer an MDX file.
form-validators.stories.mdx
import { ArgsTable } from '#storybook/addon-docs/blocks';
import { Meta } from '#storybook/addon-docs/blocks';
import { FormValidators } from './path';
<Meta
title="Components/Form Validators"
parameters={{ previewTabs: { canvas: { hidden: true } } }}
/>
<ArgsTable of={FormValidators} />

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

Gatsby image with staticQuery

I am trying for the first time GatsbyJs and I see the feature with ImageSharp for optimizing images.
Now, I created a component and it works fine, but I would like to optimize the code to be able to add more images.
The code is organized in this manner:
I have the component images.js, import this component in the index page. In the component at this moment have 2 images (1.jpg, 2.jpg)
I would like to create two returns of a single component image, see my code of images.js component below:
import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import Image from "gatsby-image"
const ImagesHome = () => {
const data = useStaticQuery(graphql`
query BioQuery {
imgOne: file(absolutePath: { regex: "/1.jpg/" }) {
childImageSharp {
fixed(width: 710) {
...GatsbyImageSharpFixed
}
}
}
imgTwo: file(absolutePath: { regex: "/2.jpg/" }) {
childImageSharp {
fixed(width: 710) {
...GatsbyImageSharpFixed
}
}
}
}
`)
return (
<div>
<Image
fixed={data.imgOne.childImageSharp.fixed}
/>
<div id="secondImageHome">
<Image
fixed={data.imgTwo.childImageSharp.fixed}
/>
</div>
</div>
)
}
export default ImagesHome
I would use the export component image in single code like:
<Img fluid={props.data.imageOne.childImageSharp.fluid} />
<Img fluid={props.data.imageTwo.childImageSharp.fluid} />
Will it be possible with my code? I tried some tutorials on YouTube, but it did not work.

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

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';

Video.js Playlists in React

I am attempting to get the React video.js example to work with the videojs-playlist plugin and I keep getting the following error: Uncaught TypeError: this.player.playlist is not a function. My component is as follows:
import React from 'react';
import videojs from 'video.js';
import 'videojs-playlist';
const VideoControl = React.createClass({
componentDidMount() {
this.player = videojs(this.videoNode);
this.player.playlist([{
sources: [{
src: 'http://media.w3.org/2010/05/sintel/trailer.mp4',
type: 'video/mp4'
}],
poster: 'http://media.w3.org/2010/05/sintel/poster.png'
}, {
sources: [{
src: 'http://media.w3.org/2010/05/bunny/trailer.mp4',
type: 'video/mp4'
}],
poster: 'http://media.w3.org/2010/05/bunny/poster.png'
}]);
},
// destroy player on unmount
componentWillUnmount() {
if (this.player) {
this.player.dispose();
}
},
render() {
return (
<div data-vjs-player>
<video ref={ node => this.videoNode = node } className="video-js"></video>
</div>
)
}
})
export default VideoControl;
videojs-playlist does not seem to be adding itself to VideoJS as a plugin. I am on the latest React and Webpack. Thanks!
It turned out to be a Webpack issue. I got it going with the following:
import 'expose-loader?videojs!../../../../node_modules/video.js/dist/video.js';
require("script-loader!../../../../node_modules/videojs-playlist/dist/videojs-playlist.js");
import videojs from 'video.js';
import videojsPlaylistPlugin from 'videojs-playlist';
videojs.registerPlugin('playlist', videojsPlaylistPlugin);
works on:
"video.js": "~7.0.3",
"videojs-playlist": "~4.2.1"

Categories