Reactjs - How to display imported images with Reactjs photo gallery - reactjs

I have been playing around with react-photo-gallery.
Have installed it together with lightbox and it works just fine when I am displaying online photos.
When I try to display imported ones it's not displaying photo but just frame of it.
import React from 'react';
import Gallery from 'react-photo-gallery';
import Lightbox from 'react-images';
import thumbsup from "../../assets/images/thumbsup.png";
const photos = [
{ src: {thumbsup}, width: 4, height: 3 },
{ src: 'https://source.unsplash.com/Dm-qxdynoEc/800x799', width: 1, height: 1 },
{ src: 'https://source.unsplash.com/qDkso9nvCg0/600x799', width: 3, height: 4 }
];
export default class Sample extends React.Component {
constructor() {
super();
this.state = { currentImage: 0 };
this.closeLightbox = this.closeLightbox.bind(this);
this.openLightbox = this.openLightbox.bind(this);
this.gotoNext = this.gotoNext.bind(this);
this.gotoPrevious = this.gotoPrevious.bind(this);
}
openLightbox(event, obj) {
this.setState({
currentImage: obj.index,
lightboxIsOpen: true,
});
}
closeLightbox() {
this.setState({
currentImage: 0,
lightboxIsOpen: false,
});
}
gotoPrevious() {
this.setState({
currentImage: this.state.currentImage - 1,
});
}
gotoNext() {
this.setState({
currentImage: this.state.currentImage + 1,
});
}
render() {
return (
<div>
<Gallery photos={photos} onClick={this.openLightbox} />
<Lightbox images={photos}
onClose={this.closeLightbox}
onClickPrev={this.gotoPrevious}
onClickNext={this.gotoNext}
currentImage={this.state.currentImage}
isOpen={this.state.lightboxIsOpen}
/>
</div>
)
}
}
I am trying to display it like I did in rest of my components.
import thumbsup from "../../assets/images/thumbsup.png";
{ src: {thumbsup}, width: 4, height: 3 }

Removing the curly braces around {thumbsub} should fix your problem.
const photos = [
{ src: thumbsup, width: 4, height: 3 },
{ src: 'https://source.unsplash.com/Dm-qxdynoEc/800x799', width: 1, height: 1 },
{ src: 'https://source.unsplash.com/qDkso9nvCg0/600x799', width: 3, height: 4 }
];
Like you have it now, the photo object would look like this:
{
src: {
thumbsup: "/..../....png"
},
width: 4,
height: 3
}

Related

React, ApexCharts, Radial Bar series value from data

I'm new to React and trying to learn. My personal project is homebrewing display site.
I want to show some of the details in radial bar. I followed tutorial and made array data file, and index file where details show. Now I'm stuck getting single values to display in radial bar.
Also values need to be calculated from percent to numeric. I got that working. I tried some push functions but did not get it to work way I wanted. My coding skills are beginner level.
display example
data.js
import product1 from '../../images/product-1.png';
import product2 from '../../images/product-1.png';
export const productData = [
{
id: 1,
img: product1,
alt: 'Beer',
name: 'Lager',
desc: 'Saaz',
ibu: '35',
ebc: '40',
abv: '8.5',
},
{
id: 2,
img: product2,
alt: 'Beer',
name: 'IPA',
desc: 'Mango, Citrus',
ibu: '85',
ebc: '25',
abv: '5.5',
},
];
index.js
import React, { Component } from 'react';
import Chart from 'react-apexcharts';
import {
ProductsContainer,
ProductWrapper,
ProductsHeading,
ProductTitle,
ProductCard,
ProductImg,
ProductInfo,
ProductDesc,
ProductIbu,
ProductEbc,
ProductAbv,
} from './ProductsElements';
const max = 119;
function valueToPercent(value) {
return (value * 100) / max;
}
class IBU extends Component {
constructor(props) {
super(props);
this.state = {
series: [valueToPercent(15)],
options: {
plotOptions: {
radialBar: {
startAngle: -90,
endAngle: 90,
hollow: {
margin: 10,
size: '70%',
background: '#222222',
image: undefined,
imageOffsetX: 0,
imageOffsetY: 0,
position: 'front',
dropShadow: {
enabled: true,
top: 5,
left: 0,
blur: 4,
opacity: 0.9,
},
},
track: {
background: '#d42d2d',
strokeWidth: '67%',
margin: 0, // margin is in pixels
dropShadow: {
enabled: true,
top: 0,
left: 0,
blur: 4,
color: '#000',
opacity: 0.6,
},
},
dataLabels: {
show: true,
name: {
offsetY: -10,
show: true,
color: '#fff',
fontSize: '17px',
},
value: {
formatter: function (value) {
return (parseFloat(value) * max) / 100;
},
color: '#dadada',
fontSize: '36px',
show: true,
},
},
},
},
fill: {
colors: [
function ({ value, seriesIndex, w }) {
if (value < 55) {
return '#7E36AF';
} else if (value >= 55 && value < 80) {
return '#164666';
} else {
return '#D9534F';
}
},
],
},
stroke: {
lineCap: 'round',
},
labels: ['IBU'],
},
};
}
render() {
return <Chart options={this.state.options} series={this.state.series} type="radialBar" height={250} />;
}
}
const Products = ({ data }) => {
return (
<ProductsContainer>
<ProductsHeading>heading</ProductsHeading>
<ProductWrapper>
{data.map((product, index) => {
return (
<ProductCard key={index}>
<ProductImg src={product.img} alt={product.alt} />
<ProductInfo>
<ProductTitle>{product.name}</ProductTitle>
<ProductDesc>{product.desc}</ProductDesc>
<ProductIbu>{product.ibu}</ProductIbu>
<IBU></IBU>
<ProductEbc>{product.ebc}</ProductEbc>
<ProductAbv>{product.abv}</ProductAbv>
</ProductInfo>
</ProductCard>
);
})}
</ProductWrapper>
</ProductsContainer>
);
};
export default Products;

breaking big component into smaller one

I'm working on separating code from index.tsx into two different files viz: firstTab.tsx and secondTab.tsx. I haven't started working on secondTab.tsx yet.
I separated first tab related code into firstTab.tsx as shown in the following code editor: The full functional code with both tabs working are in index.tsx is pasted below:
import React, { Component } from "react";
import { render } from "react-dom";
import "jqwidgets-scripts/jqwidgets/styles/jqx.base.css";
import JqxButton from "jqwidgets-scripts/jqwidgets-react-tsx/jqxbuttons";
import * as ReactDOM from "react-dom";
import JqxWindow from "jqwidgets-scripts/jqwidgets-react-tsx/jqxwindow";
import JqxInput from "jqwidgets-scripts/jqwidgets-react-tsx/jqxinput";
import JqxChart, {
IChartProps
} from "jqwidgets-scripts/jqwidgets-react-tsx/jqxchart";
import JqxGrid, {
IGridProps,
jqx
} from "jqwidgets-scripts/jqwidgets-react-tsx/jqxgrid";
import JqxTabs from "jqwidgets-scripts/jqwidgets-react-tsx/jqxtabs";
import JqxDropDownList, {
IDropDownListProps
} from "jqwidgets-scripts/jqwidgets-react-tsx/jqxdropdownlist";
import firstTab from './firstTab';
interface AppProps {}
interface AppState {
name: string;
}
interface IProps extends IGridProps {
dropdownlistSource: IDropDownListProps["source"];
}
class App extends Component<{}, IProps> {
private myTabs = React.createRef<JqxTabs>();
private gridElement = React.createRef<HTMLDivElement>();
private myGrid = React.createRef<JqxGrid>();
private gridElementTwo = React.createRef<HTMLDivElement>();
private myGrid2 = React.createRef<JqxGrid>();
constructor(props: {}) {
super(props);
this.state = {
dropdownlistSource: [
{ value: 0, label: "Affogato" },
{ value: 1, label: "Americano" },
{ value: 2, label: "Bicerin" },
{ value: 3, label: "Breve" }
]
};
}
public render() {
return (
<JqxTabs
ref={this.myTabs}
// #ts-ignore
width={400}
height={560}
initTabContent={this.initWidgets}
>
<ul>
<li style={{ marginLeft: 30 }}>
<div style={{ height: 20, marginTop: 5 }}>
<div
style={{
marginLeft: 4,
verticalAlign: "middle",
textAlign: "center",
float: "left"
}}
>
US Indexes
</div>
</div>
</li>
<li>
<div style={{ height: 20, marginTop: 5 }}>
<div
style={{
marginLeft: 4,
verticalAlign: "middle",
textAlign: "center",
float: "left"
}}
>
NASDAQ compared to S&P 500
</div>
</div>
</li>
</ul>
<div style={{ overflow: "hidden" }}>
<div id="jqxGrid" ref={this.gridElement} />
<div style={{ marginTop: 10, height: "15%" }} />
</div>
<div style={{ overflow: "hidden" }}>
<div id="jqxGrid2" ref={this.gridElementTwo} />
<div style={{ marginTop: 10, height: "15%" }} />
</div>
</JqxTabs>
);
}
private initGrid = () => {
const source = {
datafields: [{ name: "Date" }, { name: "S&P 500" }, { name: "NASDAQ" }],
datatype: "csv",
localdata: `1/2/2014,1831.98,4143.07
1/3/2014,1831.37,4131.91
1/6/2014,1826.77,4113.68
1/7/2014,1837.88,4153.18
1/8/2014,1837.49,4165.61
1/9/2014,1838.13,4156.19
2/6/2014,1773.43,4057.12
2/7/2014,1797.02,4125.86`
};
const dataAdapter = new jqx.dataAdapter(source, {
async: false,
loadError: (xhr: any, status: any, error: any) => {
console.log(xhr, status, error);
}
});
const columns: IGridProps["columns"] = [
{ cellsformat: "d", datafield: "Date", text: "Date", width: 250 },
{ datafield: "S&P 500", text: "S&P 500", width: 150 },
{ datafield: "NASDAQ", text: "NASDAQ" }
];
const grid = (
<JqxGrid
ref={this.myGrid}
width={"100%"}
height={400}
source={dataAdapter}
columns={columns}
/>
);
render(grid, this.gridElement.current!);
};
private initGrid2 = () => {
const source = {
datafields: [{ name: "Date" }, { name: "S&P 500" }, { name: "NASDAQ" }],
datatype: "csv",
localdata: `1/2/2014,1831.98,4143.07
1/3/2014,1831.37,4131.91
1/6/2014,1826.77,4113.68
1/7/2014,1837.88,4153.18
1/8/2014,1837.49,4165.61
1/9/2014,1838.13,4156.19
1/10/2014,1842.37,4174.67
2/7/2014,1797.02,4125.86`
};
const dataAdapter = new jqx.dataAdapter(source, {
async: false,
loadError: (xhr: any, status: any, error: any) => {
console.log(xhr, status, error);
}
});
const columns: IGridProps["columns"] = [
{ cellsformat: "d", datafield: "Date", text: "Date", width: 250 },
{ datafield: "S&P 500", text: "S&P 500", width: 150 },
{ datafield: "NASDAQ", text: "NASDAQ" }
];
const grid = (
<JqxGrid
ref={this.myGrid2}
width={"100%"}
height={400}
source={dataAdapter}
columns={columns}
/>
);
render(grid, this.gridElementTwo.current!);
};
private initWidgets = (tab: any) => {
switch (tab) {
case 0:
this.initGrid();
break;
case 1:
this.initGrid2();
break;
}
};
}
render(<App />, document.getElementById("root"));
Question:
Since I've already moved private initGrid = () => { inside a separate file firstTab.tsx, in index.tsx where should I put {firstTab.tsx} to make sure both tabs in index.tsx works fine? I mean, even if I comment out private initGrid = () => { function from index.tsx both tabs should work fine.
Thanks
If I would refactor this I would consider the next approach:
Create Parent component Table (probably some more appropriate name)
Create a component for US Indexes
Create a component for NASDAQ compared to S&P 500
Based on the active tab render the proper component.
You could also create a separate file that contains only exports with your data.
If you then import that into your files with the functions you can use that there, keeps it cleaner.
And if you pass that data as a prop / param to your initGrid() functions, you don't have to repeat that code, can reuse it.

React : Ag Grid Pagination Server Side

I am using AG-Grid library for my work in React JS.
I have 40000 data which I want to show using pagination (not scroll but page1, page2 , page3 and so on...).
I am totally new to it . I have used below link for reference. but it's not working.
Any one has working example ?
AG Grid Sever Side Pagination
Any help would be great.
Thank You.
"use strict";
import React, { Component } from "react";
import { render } from "react-dom";
import { AgGridReact } from "#ag-grid-community/react";
import { AllModules } from "#ag-grid-enterprise/all-modules";
import "#ag-grid-community/all-modules/dist/styles/ag-grid.css";
import "#ag-grid-community/all-modules/dist/styles/ag-theme-balham-dark.css";
class GridExample extends Component {
constructor(props) {
super(props);
this.state = {
modules: AllModules,
columnDefs: [
{ field: "id" },
{
field: "athlete",
width: 150
},
{ field: "age" },
{ field: "country" },
{ field: "year" },
{ field: "sport" },
{ field: "gold" },
{ field: "silver" },
{ field: "bronze" }
],
defaultColDef: {
width: 120,
resizable: true
},
rowModelType: "serverSide",
cacheBlockSize: 100,
maxBlocksInCache: 10
};
}
onGridReady = params => {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
const httpRequest = new XMLHttpRequest();
const updateData = data => {
var idSequence = 0;
data.forEach(function(item) {
item.id = idSequence++;
});
var server = new FakeServer(data);
var datasource = new ServerSideDatasource(server);
params.api.setServerSideDatasource(datasource);
};
httpRequest.open(
"GET",
"https://raw.githubusercontent.com/ag-grid/ag-grid/master/packages/ag-grid-docs/src/olympicWinners.json"
);
httpRequest.send();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
updateData(JSON.parse(httpRequest.responseText));
}
};
};
render() {
return (
<div style={{ width: "100%", height: "100%" }}>
<div style={{ height: "100%", paddingTop: "26px", boxSizing: "border-box" }}>
<div
id="myGrid"
style={{
height: "100%",
width: "100%"
}}
className="ag-theme-balham-dark"
>
<AgGridReact
modules={this.state.modules}
columnDefs={this.state.columnDefs}
defaultColDef={this.state.defaultColDef}
rowModelType={this.state.rowModelType}
cacheBlockSize={this.state.cacheBlockSize}
maxBlocksInCache={this.state.maxBlocksInCache}
animateRows={true}
pagination={true}
onGridReady={this.onGridReady}
/>
</div>
</div>
</div>
);
}
}
function ServerSideDatasource(server) {
return {
getRows: function(params) {
setTimeout(function() {
var response = server.getResponse(params.request);
if (response.success) {
params.successCallback(response.rows, response.lastRow);
} else {
params.failCallback();
}
}, 500);
}
};
}
function FakeServer(allData) {
return {
getResponse: function(request) {
console.log("asking for rows: " + request.startRow + " to " + request.endRow);
var rowsThisPage = allData.slice(request.startRow, request.endRow);
var lastRow = allData.length <= request.endRow ? data.length : -1;
return {
success: true,
rows: rowsThisPage,
lastRow: lastRow
};
}
};
}
Try this lines of react code which is mention in documentation. If it will not work, for more precise answer please share your implemented code.

images getting rotated in react app

This is my code
import React from "react";
import { Grid, Header } from "semantic-ui-react";
import Gallery from "react-photo-gallery";
import Lightbox from "react-images";
import _1 from "../images/pics/2.jpg";
import _2 from "../images/pics/1.jpg";
import _3 from "../images/pics/3.jpg";
import _4 from "../images/pics/4.jpg";
import _5 from "../images/pics/5.jpg";
import _6 from "../images/pics/6.jpg";
import _7 from "../images/pics/7.jpg";
import _8 from "../images/pics/8.jpg";
import _9 from "../images/pics/9.jpg";
const photos = [
{
src: _1,
width: 4,
height: 3
},
{
src: _2,
width: 2,
height: 2
},
{
src: _3,
width: 2,
height: 2
},
{
src: _4,
width: 2,
height: 2
},
{
src: _5,
width: 2,
height: 2
},
{
src: _6,
width: 2,
height: 2
},
{
src: _7,
width: 2,
height: 2
},
{
src: _8,
width: 2,
height: 2
},
{
src: _9,
width: 2,
height: 2
}
];
class SiteGalleryPage extends React.Component {
constructor() {
super();
this.state = {
currentImage: 0,
lightboxIsOpen: false
};
}
openLightbox = (event, obj) => {
this.setState({
currentImage: obj.index,
lightboxIsOpen: true
});
};
closeLightbox = () => {
this.setState({
currentImage: 0,
lightboxIsOpen: false
});
};
gotoPrevious = () => {
this.setState({
currentImage: this.state.currentImage - 1
});
};
gotoNext = () => {
this.setState({
currentImage: this.state.currentImage + 1
});
};
render() {
return (
<Grid>
<Grid.Row centered>
<Header color="teal" as="h2">
Site Gallery
</Header>
</Grid.Row>
<Grid.Row>
<div>
<Gallery photos={photos} onClick={this.openLightbox}
/>
<Lightbox
images={photos}
isOpen={this.state.lightboxIsOpen}
onClickPrev={this.gotoPrevious}
onClickNext={this.gotoNext}
currentImage={this.state.currentImage}
onClose={this.closeLightbox}
/>
</div>
</Grid.Row>
</Grid>
);
}
}
export default SiteGalleryPage;
I am using react-images, react-photo-gallery libraries.
Some of the images are getting rotated when they are visible in the browser.
But they are good when they saved in folder. They are all clicked with a mobile but some of them are only getting rotated.
Please help me how to fix this up!.

Cytoscape and ReactJS integration

I am trying to use use Cytoscape with ReactJS and some how nothing is getting displayed in the simple component i am trying.
Here is the code. I am returning an empty object in mapStateToProps as i am trying to display a static graph where i have hard coded the edges and nodes.
Cytoscape version i am using is from my package.json
"cytoscape": "^2.7.6",
"react": "^15.2.1",
Here is the Cyctoscape jsbin i am using for my sample.
enter link description here
Appreciate any help.
Thanks
import React,{Component} from 'react';
import cytoscape from 'cytoscape';
import {connect} from 'react-redux';
import { bindActionCreators } from 'redux';
class GraphContainer extends React.Component{
constructor(props){
super(props);
this.renderCytoscapeElement = this.renderCytoscapeElement.bind(this);
}
renderCytoscapeElement(){
console.log('* Cytoscape.js is rendering the graph..');
this.cy = cytoscape(
{
container: document.getElementById('cy'),
boxSelectionEnabled: false,
autounselectify: true,
style: cytoscape.stylesheet()
.selector('node')
.css({
'height': 80,
'width': 80,
'background-fit': 'cover',
'border-color': '#000',
'border-width': 3,
'border-opacity': 0.5,
'content': 'data(name)',
'text-valign': 'center',
})
.selector('edge')
.css({
'width': 6,
'target-arrow-shape': 'triangle',
'line-color': '#ffaaaa',
'target-arrow-color': '#ffaaaa',
'curve-style': 'bezier'
})
,
elements: {
nodes: [
{ data: { id: 'cat' } },
{ data: { id: 'bird' } },
{ data: { id: 'ladybug' } },
{ data: { id: 'aphid' } },
{ data: { id: 'rose' } },
{ data: { id: 'grasshopper' } },
{ data: { id: 'plant' } },
{ data: { id: 'wheat' } }
],
edges: [
{ data: { source: 'cat', target: 'bird' } },
{ data: { source: 'bird', target: 'ladybug' } },
{ data: { source: 'bird', target: 'grasshopper' } },
{ data: { source: 'grasshopper', target: 'plant' } },
{ data: { source: 'grasshopper', target: 'wheat' } },
{ data: { source: 'ladybug', target: 'aphid' } },
{ data: { source: 'aphid', target: 'rose' } }
]
},
layout: {
name: 'breadthfirst',
directed: true,
padding: 10
}
});
}
componentDidMount(){
this.renderCytoscapeElement();
}
render(){
return(
<div className="node_selected">
<div style="{height:'400px';width:'400px'}" id="cy"/>
</div>
)
}
}
function mapStateToProps(state){
return {};
}
export default connect(mapStateToProps,null)(GraphContainer);
For those still looking for how to get the code posted working - I was able to get it working by modifying the cy div, specifying its style with non-zero height and width.
render() {
let cyStyle = {
height: '1000px',
width: '1000px',
margin: '20px 0px'
};
return (
<div>
<div style={cyStyle} id="cy"/>
</div>
);
}
I had to integrate cytoscape.js with react as well, but no redux, so wrote a gist in case anybody else needs it.
code example
I am able to resolve the Issue. I missed the Styles for the Layer itself and hence it is defaulting to 0px height and 0px width.
Thanks
For a basic version of the above using the cytoscape "Getting Started" example and using React hooks you can do this:
import React, {Fragment, useEffect, useRef} from 'react';
import cytoscape from 'cytoscape'
const GraphTest = () => {
const graphRef = useRef(null)
const drawGraph = () => {
const cy = cytoscape({
container: graphRef.current,
elements: [
{ data: { id: 'a' } },
{ data: { id: 'b' } },
{
data: {
id: 'ab',
source: 'a',
target: 'b'
}
}]
})
}
useEffect(() => {
drawGraph()
}, [])
return (
<Fragment>
<h2>Graph Test</h2>
<div ref={graphRef} style={{width: '100%', height: '80vh'}}>
</div>
</Fragment>
)
}
export default GraphTest

Resources