Duplicate image shown - useEffect issue? - reactjs

I have some code to display my board as shown below:
<Grid item xs={6} justify="center">
<Paper id="board">
</Paper>
</Grid>
But sometimes when I save my code, it displays a duplicate board on the screen on localhost:3000, although not always. Example below:
I am suspecting it it might have something to do with my useEffect:
useEffect(() => {
// componentDidMount() {
const board = new Gameboard(document.getElementById('board'), {
// position: 'r4r1k/p1P1qppp/1p6/8/5B2/2Q1P3/P4PPP/R3KB1R b KQ - 0 21',
position: game.fen(),
sprite: {
url: './gameboard-sprite.svg', // pieces and markers are stored as svg in the sprite
grid: 40, // the sprite is tiled with one piece every 40px
cache: true,
},
orientation: COLOR.white,
moveInputMode: MOVE_INPUT_MODE.dragPiece,
responsive: true,
});
board.enableMoveInput(inputHandler);
}, []);
Any idea why it could be displaying twice, but only sometimes? It always removes the duplicate board when I click the browser refresh button if that helps. But it is often there when I first save my code.

Save your Gameboard instance in useRef, this way only one instance is created:
const board = useRef();
useEffect(() => {
if(!board.current) {
board.current = new Gameboard(document.getElementById('board'), {
// position: 'r4r1k/p1P1qppp/1p6/8/5B2/2Q1P3/P4PPP/R3KB1R b KQ - 0 21',
position: game.fen(),
sprite: {
url: './gameboard-sprite.svg', // pieces and markers are stored as svg in the sprite
grid: 40, // the sprite is tiled with one piece every 40px
cache: true,
},
orientation: COLOR.white,
moveInputMode: MOVE_INPUT_MODE.dragPiece,
responsive: true,
});
board.current.enableMoveInput(inputHandler);
}
}, []);

You need to return cleanup function from effect, so when fast refresh will rerun it, there will be no duplicates. It works properly sometimes because sometimes fast refresh sometimes don't try to preserve state and renders everything as new. This depends on changes you made, so when you change one file it will render clean, but on another files it will try to preserve state and only rerun effects (this is where second board added).
Also, it is better not to interact with DOM directly and use ref instead. This is better way to work with DOM in react, since it's react main purpose to update DOM.

Related

Is it bad practice to access HTML elements by ID in React TypeScript?

I was told at a previous job that I should never access HTML elements directly through means like getElementById in React TypeScript. I'm currently implementing Chart.js. For setting up the chart, I was initially using a useRef hook instead of accessing context, but now it seems like I need to grab the canvas by ID in order to instantiate it properly. I want to know if this is kosher.
I suspect something is wrong with me not using a context, because my chart data doesn't load and throws a console error: "Failed to create chart: can't acquire context from the given item"
useEffect(() => {
chart = new Chart(chartRef.current, {
type: "bar",
data: {
labels: labelsArray.map((label) => {
const date = new Date(label);
// add one because month is 0-indexed
return date.getUTCMonth() + 1 + "/" + date.getUTCDate();
}),
datasets: [
{
data: valuesArray,
backgroundColor: "#1565C0",
borderRadius: 6,
},
],
},
options: {
interaction: { mode: "index" },
onHover: (event, chartElement) => {
const target = event.native.target;
(target as HTMLInputElement).style.cursor = chartElement[0]
? "pointer"
: "default";
},
plugins: {
tooltip: {
mode: "index",
enabled: true,
},
title: {
display: true,
text: "Daily Usage Past 30 Days",
align: "start",
fullSize: true,
font: {
size: 24,
},
padding: {
bottom: 36,
},
},
},
scales: {
x: {
display: false,
},
},
elements: {
line: {
borderJoinStyle: "round",
},
},
},
});
return () => {
chart.destroy();
};
}, [labelsArray, valuesArray]);
and HTML:
<div className="mt-80 ml-12 p-8 shadow-lg border-2 border-slate-100 rounded-xl items-center">
<canvas id="chart" ref={chartRef}></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</div>
Also, per the Chart.js documentation: "To create a chart, we need to instantiate the Chart class. To do this, we need to pass in the node, jQuery instance, or 2d context of the canvas of where we want to draw the chart." Not sure how we would do this with a useRef
Yes,
It is not good practice to access dom elements directly through document API.
Because in react
virtual dom is responsible for painting/ re-rendering the UI.
State updation is the proper way to tell react to trigger re-render.
The flow is state updation -> calculate differences -> find who over is using that state -> grab those components -> re-render only those components.
virtual dom is the source of truth for react to render and update actual DOM.
Now, If you directly access some dom elements and do some operation on it, like updating, react will never know that some change has happened and it will basically break the flow of the react, in which case there will be no reason to use react.js
The flow would be accessing some dom element -> updating -> displaying.
The problem with this approach if react encounters that later what i have in virtual dom is not actual presentation in the actual dom, which will create mess.
That is the reason there is useRef hook to manipulate dom.

Re-rendering a component with useSpring resets animation chain and over time makes other animations staggery

I have this spring defining a looped animation:
const style = useSpring({
from: { marginBottom: 0 },
to: [
{ marginBottom: 0 },
{ marginBottom: 80, config: { duration: 600 }, delay: 3000 },
{ marginBottom: -80, config: { duration: 0 } },
{ marginBottom: 0, config: { duration: 600, delay: 1000 } },
],
loop: true,
})
My problem is that whenever I re-render the component containing the spring, the animation 'resets' and starts moving towards the first to position (in this case { martinBottom: 0 })
It can be seen in this sandbox - click the 'reset' button just as the arrow is traveling up and it will reverse course instantly
The documentation also hints that stabilizing the references of from and to may solve the issue... and it kind of does, but it introduces a new one: if the components re-renders shortly before the animation starts, it skips the 'travel up' portion: sandbox here.
The bigger problem is that the more times I 'interrupt' the animation cycle by re-rendering, the more it affects some of my other, more demanding animations, making them more and more staggered.
Refreshing whole app instantly resets this decay and makes all animations fluid again. When I remove this useSpring from my code, this decay disappears
So what is going on there? Is there something I'm missing?
From this docs example, It makes sense to me that the animation resets on re-render ... but then why does this example instruct me to compose staged animations this way, am I missing some key step?
And what's up with this slow 'decay' of other animations' performance, is that a known cause to that?

React blueimp-load-image rescaling of uploaded image

I'm using the package blueimp-load-image package to load an image in my react application. The image should be resized and put into a canvas afterwards.
This is my code that handles the upload. It can only be an image.
const handleImageUpload = e => {
const [file] = e.target.files;
if (file) {
loadImage(
file,
img => {
setImage(img);
changeOffset(img);
},
{
orientation: true,
maxWidth: innerWidth,
maxHeight: innerHeight,
downsamplingRatio: 0.25,
pixelRatio: window.devicePixelRatio,
imageSmoothingEnabled: true,
imageSmoothingQuality: 'high',
canvas: false,
contain: true,
}
);
}
};
The img gets put into a state variable that gets shown in my canvas (I'm using a KonvaImage from react-konva for that). My problem is that if I don't use pixelRatio: window.devicePixelRatio, the image gets shown correctly, but the quality is poor. If I, however, use pixelRatio: window.devicePixelRatio, the picture is zoomed in.
If I log out the img inside the loadImage this is the output. The first one without pixelRatio, the second one with pixelRatio.
This is what the image on the screen looks like (again first one without pixelRation, the second one with pixelRatio):
I hope somebody can help me with my problem. I would of course also be open for a different way of resizing the images if it works better.
Thanks in advance!

How to get lat lang of top left and bottom right of map when zoomed

I am trying to get top left and right bottom of the Map which i am displaying. And i am trying to get this particular data in zoom event, but somehow this.map is becoming undefined and breaking the application
this.map.on('zoomend', function (layer) {
console.log("zoom",layer.target._zoom)
console.log("getbounds", this.map.getBounds());
});
Below i am providing the componentDidMount, here only i am defining zoom event, which working fine if i simply console.
componentDidMount() {
/* We are loading the map here whether or not load has loaded */
this.map = L.map('map', {
center: [50, 10],
zoom: 3,
minZoom: 2,
maxZoom: 11,
zoomControl: false,
attributionControl: false,
scrollwheel: false,
legends: true,
infoControl: false,
});
console.log("getbounds", this.map.getBounds()); //WORKING BUT JUST ONCE, when this component mounts.
this.map.on('zoomend', function (layer,a) {
console.log("zoom",layer.target._zoom)
console.log("zoom",layer)
console.log("a",a)
console.log("getbounds", this.map.getBounds()); // NOT WORKING, this.map GETS UNDEFINED which is obvious also.
});
/* Giving zoom control a different place in UI */
L.control.zoom({ position: 'topright' }).addTo(this.map);
L.control.scale({ position: "topright" }).addTo(this.map);
/* Selecting and showing styles for the map */
L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', {
}).addTo(this.map);
}
Just change this part of your code bro
this.map.on('zoomend', (layer,a) => {
console.log("zoom",layer.target._zoom)
console.log("zoom",layer)
console.log("a",a)
console.log("getbounds", this.map.getBounds()); // NOT WORKING, this.map GETS UNDEFINED which is obvious also.
});
The reason why your code did not work is you were using simple function as a callback which need to bind to use this.
Solution: Use arrow function

ExtJS Carousel Implementation

I'm trying to make a carousel for displaying images, I got most of the functionality from a solution someone in sencha forums came up with. I made a few adjustments to the code and got it working at first glance.
Here's the original code on sencha forums...
http://www.sencha.com/forum/showthread.php?256456-an-Ext-JS-4-carousel-component&p=938789#post938789
This didn't work on ExtJS 4 so I made a few modifications for it to work and also to make it look better (to my eyes). Here's how it looks
I do have a problem or two though...
First off I can't figure out how to add a text over the images I'm displaying, I managed to add that line of text in the center but I also want to add a date to the images and that should display on top of each image container. I think it's pretty basic, but I can't figure out how... I don't have a full understanding of HTML, so that's not helping.
Secondly, and most important, I'm getting some weird behaviour when I close and reopen the window containing this carousel. I've seen this kind of behaviour before when using the same ID in multiple instances of a view in ExtJS, but I have changed all IDs to generate a new one whenever a new carousel window opens and still experience the same problem.
Here's what happens when I close and reopen the window...
And that happens with every window I open after closing the carousel
And last but not least!! I can't get the keydown event to work on this window, I have no clue why. I've tried setting the listener on the carousel container instead of the window but still get no firing whatsoever.
This is the code I'm using to create the carousel window...
var win = Ext.create('Ext.view.CarouselWindow');
win.show();
Ext.createWidget('carousel',{
xPos: win.getSize().width/2,
yPos: win.getSize().height/4,
FPS: 70,
reflHeight: 56,
height:'100%',
width:'100%',
reflGap:2,
bringToFront:true,
store:store,
images:store,
altBox:'imageNameLabel',
autoRotate: 'no',
renderTo: 'carousel-div',
listeners:{
keydown:function(){
console.log('asdasd')
}
}
});
This is the initComponent of the carousel component, which is rendered in the window.
initComponent: function(config) {
this.callParent(arguments);
this.container = this.renderTo ? Ext.get(this.renderTo) : this.up('container');
if (this.xRadius === 0){
this.xRadius = (this.container.getWidth()/2.3);
}
if (this.yRadius === 0){
this.yRadius = (this.container.getHeight()/6);
}
this.xCentre = this.xPos;
this.yCentre = this.yPos;
// Start with the first item at the front.
this.rotation = this.destRotation = Math.PI/2;
this.timeDelay = 1000/this.FPS;
// Turn on the infoBox
if(this.altBox !== '')
// Ext.get(this.altBox).applyStyles({display: 'block'});
if(this.titleBox !== '')
Ext.get(this.titleBox).applyStyles({display: 'block'});
//
// Turn on relative position for container to allow absolutely positioned elements
// within it to work.
this.container.applyStyles({ position:'relative', overflow:'hidden'});
// Setup the store.
this.initStore();
this.setUpContainerListener();
this.innerWrapper = this.container.createChild({
tag: 'div',
style: 'position:absolute;width:100%;height:100%;'
});
this.checkImagesLoaded();
},
And here's the Image component that the carousel uses...
/**
* #author Aymen ABDALLAH <aymen.abdallah#gmail.com>
* #docauthor Aymen ABDALLAH
*/
Ext.define('Ext.component.Image', {
config: {
orgWidth: 400,
orgHeight: 400,
reflHeight: 0,
reflOpacity: 0,
itemIndex: 0,
image: null,
reflection: null,
container: null,
alt: '',
title: '',
imageSrc: '',
imageOK: false
},
// id: '',
constructor: function(config){
this.initConfig(config);
this.imageOK = true;
this.image = new Ext.Element(document.createElement('img'));
this.image.set({
// id: this.id,
src: this.imageSrc,
class : 'carousel-image',
alt: this.alt,
title: this.title
});
this.image.setStyle({position : 'absolute'}); // This seems to reset image width to 0 on webkit!
},
setUpReflection: function(){
if (this.reflHeight > 0)
{
this.reflection = Ext.create('Ext.component.Reflection', {
imageHeight: this.orgHeight,
imageWidth: this.orgWidth,
image: this.image,
parent: this.container,
reflHeight: this.reflHeight,
reflOpacity: this.reflOpacity
});
}
},
generateId: function(){
// return Ext.data.UuidGenerator.create().generate();
},
getImage: function(){
return this.image;
}
});
I didn't want to flood this with code so I restricted to what I think might be useful, there might be some missing though, in that case just tell me and I'll update the post with the portion of the code you need.
EDIT
Here's a link to sencha fiddle showing the carousel and the error. To see the second error open the carousel by clicking the button, close it with ESC and then try to open it once again. You'll notice it either doesn't show or it shows like the screenshot I posted.
https://fiddle.sencha.com/#fiddle/2iu
EDIT 2
Just found out the problem comes from the images, if I comment these lines:
this.image = new Ext.Element(document.createElement('img'));
this.image.set({
id: this.id,
src: this.imageSrc,
class : 'carousel-image',
alt: this.alt,
title: this.title
});
the second error I listed disappears. Of course this is not a solution as the carousel won't display any image this way, but I thought this could be a useful piece of data for anyone interested in helping.
For those who visit this page (I know it's an old post),
The issue isn't actually with the second view, the first view causes a layout error.
The Ext.component.Image class is missing a render function, to fix this add
render: function () {
return;
}
to the class.
Not sure how to fix the other issue entirely, but you could change the image component to be a form/panel and have text, or use the caption tags.

Resources