Displaying Scroll Direction On Infinite Scrolling Div -- React - reactjs

So I'm trying to create an infinite scroll component that will display if the component is scrolling left, right, or not at all. I'm running into alot of issues using hooks. Ive tried combining this https://dirask.com/posts/React-scroll-stop-event-DkBe01 with this https://codesandbox.io/s/icy-river-wr0uk?file=/src/App.js but could not get it functioning. Lastly, any ideas why it smoothly transitions when I scroll right but it stops upon scrolling left? Thank you guys for your help, this is my first post and I appreciate any help from the community!
import React, { Component, useEffect, useRef, useReducer, useState } from 'react'
import Card from './Card'
import './skills.scss'
import myImage from './Images/editIcon.png'
function SkillsFunction() {
const [state, setState] = useReducer(
(state, newState) => ({...state, ...newState}),
{disableScroll: false, scrollWidth: 0, scrollPos: 1, clonesWidth: 0}
);
const scrollContainerRefy = useRef();
function reCalc() {
let scrollPos = scrollPos;
let scrollWidth = scrollContainerRefy.current.clientWidth;
let clonesWidth = getClonesWidth();
if (scrollPos <= 0) {
scrollPos = 1;
}
setState({
scrollPos: scrollPos,
scrollWidth: scrollWidth,
clonesWidth: clonesWidth,
});
};
// function sideScroll(element,direction,speed,distance,step) {
// let scrollAmount = 0;
// var slideTimer = setInterval(() => {
// if(direction == 'left'){
// element.scrollLeft -= step;
// } else {
// element.scrollLeft += step;
// }
// scrollAmount += step;
// if(scrollAmount >= distance){
// window.clearInterval(slideTimer);
// }
// }, speed);
// };
function handleScroll(e) {
const container = e.currentTarget;
const scrollWidth = container.scrollWidth;
const clonesWidth = getClonesWidth();
let scrollPos = container.scrollLeft;
let scrollPosAdd;
container.clientWidth > clonesWidth ? scrollPosAdd = container.clientWidth : scrollPosAdd = clonesWidth;
if (!state.disableScroll) {
if (scrollPos + scrollPosAdd >= scrollWidth) {
setScroll(
// The math floor value helps smooth out the scroll jump,
// I don't know why that particular value works, but it does
// Same goes for the other setScroll call below
container, 1
// + Math.floor(scrollPosAdd/50)
);
setState({
disableScroll: true,
});
} else if (scrollPos <= 0) {
setScroll(
container, scrollWidth - clonesWidth
// - Math.floor(scrollPosAdd/50)
);
setState({
disableScroll: true,
});
}
}
setState({
scrollWidth: container.scrollWidth,
scrollPos: container.scrollLeft,
});
} ;
function getClonesWidth() {
const clones = document.getElementsByClassName('is-clone');
let clonesWidth = 0;
for (let i = 0; i < clones.length; i++) {
clonesWidth = clonesWidth + clones[i].clientWidth;
}
return clonesWidth;
};
function setScroll(element, pos) {
element.scrollLeft = pos;
setState({
scrollPos: element.scrollLeft,
});
};
function scrollNext(e) {
const container = e.currentTarget.previousSibling;
const element = container;
const direction = 'right';
const speed = 10;
const distance = 272;
const step = 10;
let scrollAmount = 0;
var slideTimer = setInterval(() => {
if(direction == 'left'){
element.scrollLeft -= step;
} else {
element.scrollLeft += step;
}
scrollAmount += step;
if(scrollAmount >= distance){
window.clearInterval(slideTimer);
}
}, speed);
};
function scrollPrev(e) {
const container = e.currentTarget.nextSibling;
const element = container;
const direction = 'left';
const speed = 10;
const distance = 272;
const step = 10;
let scrollAmount = 0;
var slideTimer = setInterval(() => {
if(direction == 'left'){
element.scrollLeft -= step;
} else {
element.scrollLeft += step;
}
scrollAmount += step;
if(scrollAmount >= distance){
window.clearInterval(slideTimer);
}
}, speed);
};
// function componentDidUpdate(prevProps, prevState) {
// };
// function componentDidMount() {
// window.addEventListener('resize', reCalc);
// };
// function componentWillUnmount() {
// window.removeEventListener('resize', reCalc);
// };
useEffect(() => {
// Update the document title using the browser API
if (state.disableScroll) {
window.setTimeout(function() {
setState({
disableScroll: false,
});
}, 40)
}
});
const [scrollDir, setScrollDir] = useState("scrolling left");
const containerRef = useRef();
useEffect(() => {
console.log("olay");
const threshold = 0;
let lastScrollX = window.scrollX;
let ticking = false;
const updateScrollDir = () => {
const scrollX = window.scrollX;
if (Math.abs(scrollX - lastScrollX) < threshold) {
ticking = false;
return;
}
setScrollDir(
scrollX > lastScrollX ? "scrolling right" : "scrolling left"
);
lastScrollX = scrollX > 0 ? scrollX : 0;
ticking = false;
};
const onScroll = () => {
if (!ticking) {
window.requestAnimationFrame(updateScrollDir);
ticking = true;
}
};
window.addEventListener("scroll", onScroll);
console.log(scrollDir);
return () => window.removeEventListener("scroll", onScroll);
}, [scrollDir]);
return(
<>
<div className="card-container">
<div className="scroll scroll-prev" onClick={scrollPrev}>
<i className="fas fa-chevron-left"></i>
</div>
<div ref={containerRef} className="scrolling-wrapper" onScroll={handleScroll}>
<Card title={'Card Number 7'} classes={""}/>
<Card title={'Card Number 1'} classes={""}/>
<Card title={'Card Number 2'}/>
<Card title={'Card Number 3'}/>
<Card title={'Card Number 4'}/>
<Card title={'Card Number 5'}/>
<Card title={'Card Number 6'} image={myImage}/>
<Card title={'Card Number 7'} classes={"is-clone is-start"}/>
<Card title={'Card Number 1'} classes={"is-clone"}/>
<Card title={'Card Number 2'} classes={"is-clone"}/>
<Card title={'Card Number 3'} classes={"is-clone"}/>
<Card title={'Card Number 4'} classes={"is-clone"}/>
<Card title={'Card Number 5'} classes={"is-clone"}/>
<Card title={'Card Number 6'} classes={"is-clone"}/>
</div>
<div className="scroll scroll-next" onClick={scrollNext}>
<i className="fas fa-chevron-right"></i>
</div>
</div>
<div>Scrolling </div>
</>
)
}
export default SkillsFunction

Related

create linked list in React - Expanding on the React Tic-Tac-Toe Tutorial

I'm trying to expand on the official react Tic-Tac-Toe tutorial: https://reactjs.org/tutorial/tutorial.html#completing-the-game by creating a linked list to search for the win condition. However, I am having issues accessing the information. Does anyone know where I'm going wrong? I keep getting undefined with my console.log on line 138
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
function Square(props) {
return (
\<button className="square" onClick={props.onClick}\>
{props.value}
{props.rightmiddle}
{props.righttop}
{props.rightbottom}
{props.lefttop}
{props.leftbottom}
{props.top}
{props.bottom}
\</button\>
);
}
class Board extends React.Component {
renderSquare(i) {
return (
\<Square
value={this.props.squares\[i\]}
rightmiddle = {null}
righttop = {null}
rightbottom = {null}
leftmiddle = {null}
lefttop = {null}
leftbottom = {null}
top = {null}
bottom = {null}
onClick={() =\>
this.props.onClick(i)
}
/\>
);
}
forloop(x){
const numcolumns = 3;
const options = [];
for (let i = 0; i < numcolumns; i++) {
options.push(this.renderSquare(i + x));
}
return (
<div className="board-row">
{options}
</div>
)
}
render() {
const numrows = 3;
const linklistTRow = [];
const linklistBRow = [];
const linklistMRow = [];
const rows = [];
for(let i = 0; i < numrows; i++)
{
rows.push(this.forloop(i*numrows));
if (i === 0) { linklistTRow.push(rows[0])};
if (i === 1) { linklistMRow.push(rows[1])};
if (i === 2) { linklistBRow.push(rows[2])};
};
return (
<div> {rows} </div>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
history: \[{
squares: Array(9).fill(null),
}\],
stepNumber: 0,
xIsNext: true,
};
}
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history\[history.length - 1\];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares\[i\]){
return;
}
squares\[i\] = this.state.xIsNext ? 'X' : 'O';
this.setState({
history: history.concat(\[{
squares: squares,
}\]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext,
});
}
jumpTo(step) {
this.setState({
stepNumber: step,
xIsNext: (step % 2) === 0,
});
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
const moves = history.map((step, move) => {
const desc = move ?
'Go to move #' + move :
'Go to game start';
return (
<li key={move}>
<button onClick = {() => this.jumpTo(move)}>{desc}
</button>
</li>
);
});
let status;
if (winner) {
status = 'Winner: ' + winner;
}
else {
status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
}
return (
<div className="game">
<div className="game-board">
<Board
squares = {current.squares}
onClick={(i) => this.handleClick(i)}
log = {console.log(this.props.value)}
/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{moves}</ol>
</div>
</div>
);
}
}
// ========================================
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(\<Game /\>);
function calculateWinner(squares) {
const lines = \[
\[0, 1, 2\],
\[3, 4, 5\],
\[6, 7, 8\],
\[0, 3, 6\],
\[1, 4, 7\],
\[2, 5, 8\],
\[0, 4, 8\],
\[2, 4, 6\],
\];
for (let i = 0; i \< lines.length; i++) {
const \[a, b, c\] = lines\[i\];
if (squares\[a\] && squares\[a\] === squares\[b\] && squares\[a\] === squares\[c\]) {
return squares\[a\];
}
}
return null;
}
I have been trying to use props.value to call the square number (0 to 8) however, this is showing undefined results.

Keep random numbers consistent after state change in React

I'm making a Nextjs app, and on one page I create an array of numbers that is shuffled using a random number. The problem is that every time the state changes, the component gets rendered so the array gets re-shuffled. I need the original shuffle to stay consistent. Here's the relevant code:
export default function Game() {
const { query } = useRouter();
const [cardsFlipped, setCardsFlipped] = useState(
Array(query.tileNumber).fill(false)
);
let counter = query.tileNumber / 2;
let iconSet = [...Array(counter).keys()];
while (counter > 0) {
const index = Math.floor(Math.random() * iconSet.length);
tiles.push(iconSet.splice(index, 1));
counter--;
}
const tileOrder = tiles.concat(tiles).sort((a, b) => 0.5 - Math.random());
const handleFlip = (index) => {
if (cardsFlipped[index] === false) {
setCardsFlipped((prev) =>
prev.map((el, i) => {
if (i === index) {
return true;
}
return el;
})
);
setTimeout(() => {
setCardsFlipped((prev) =>
prev.map((el, i) => {
if (i === index) {
return false;
}
return el;
})
);
}, query.tileTransition * 1000);
}
};
let cards = tileOrder.map((e, i) => (
<ReactCardFlip
isFlipped={cardsFlipped[i]}
flipDirection="horizontal"
key={"card" + i + "-" + e}
>
<Card
iconSet={2}
index={50}
callback={() => {
handleFlip(i);
}}
/>
<Card iconSet={parseInt(query.icons)} index={e} callback={handleFlip} />
</ReactCardFlip>
));
return (<div>{cards}</div>);
}
I thought of converting it into a class, and having a constructor, but then I get an error that useRouter can't be used in classes.
You just need to wrap your logic in a useEffect, something like this:
export default function Test() {
const { query } = useRouter();
const [cardsFlipped, setCardsFlipped] = useState(
Array(query.tileNumber).fill(false)
);
const [tileOrder, setTileOrder] = useState([]);
useEffect(() => {
let counter = query.tileNumber / 2;
let iconSet = [...Array(counter).keys()];
while (counter > 0) {
const index = Math.floor(Math.random() * iconSet.length);
tiles.push(iconSet.splice(index, 1));
counter--;
}
setTileOrder(tiles.concat(tiles).sort((a, b) => 0.5 - Math.random()));
}, []);
const handleFlip = index => {
if (cardsFlipped[index] === false) {
setCardsFlipped(prev =>
prev.map((el, i) => {
if (i === index) {
return true;
}
return el;
})
);
setTimeout(() => {
setCardsFlipped(prev =>
prev.map((el, i) => {
if (i === index) {
return false;
}
return el;
})
);
}, query.tileTransition * 1000);
}
};
let cards = tileOrder.map((e, i) => (
<ReactCardFlip
isFlipped={cardsFlipped[i]}
flipDirection="horizontal"
key={'card' + i + '-' + e}
>
<Card
iconSet={2}
index={50}
callback={() => {
handleFlip(i);
}}
/>
<Card iconSet={parseInt(query.icons)} index={e} callback={handleFlip} />
</ReactCardFlip>
));
return <div>{cards}</div>;
}

react konva animation to follow a path

Hey I am new to react konva and wanted to create an animation in which a rectangle follows a user defined path of dots. First user defines the path by clicking on screen and initializing the destination dots and then the rectangle should follow the path accordingly
const [coords, setCoords] = useState([]); //path dots variable
const [points, setPoints] = useState([250, 250]); //rectangle x,y variable
const ref= useRef(null);
const [check, setCheck] = useState(false); //check wheather user has clicked the start tracing button
const [i, setI] = useState(0); //index state variable
const handleStart= () => {
if (check === false) {
setCheck(true);
} else {
setCheck(false);
}
};
const handleClick = (e) => {
if (check === false) {
var stage = e.target.getStage();
var newcoord = stage.getPointerPosition();
var temp = [newcoord.x, newcoord.y];
setCoords((coords) => [...coords, temp]);
}
};
useEffect(() => {
if (!check) {
return;
}
var node = ref.current;
var anim = new Konva.Animation(function (frame) {
if (frame.time / 10 >= coords[i][0]) {
alert("reached");
setPoints([coords[i][0], coords[i][1]]);
setI(i + 1);
} else {
node.x(frame.time / 10);
}
if (frame.time / 10 >= coords[i][1]) {
alert("reached");
setPoints([coords[i][0], coords[i][1]]);
setI(i + 1);
} else {
node.y(frame.time / 10);
}
}, node.getLayer());
anim?.start();
return () => anim?.stop();
}, [check, i]);
return (
<div>
<Stage
onMouseDown={(e) => handleClick(e)}
width={window.innerWidth}
height={window.innerHeight}
>
<Layer>
<Group >
<Rect
width={50}
height={50}
x={points[0]}
y={points[1]}
strokeWidth={2}
fill="black"
opacity={1}
draggable
ref={ref}
/>
</Group>
{coords.map((key, index) => (
<Circle
x={key[0]}
y={key[1]}
numPoints={1}
radius={4}
fill="black"
strokeWidth={2}
/>
))}
</Layer>
</Stage>
<Button onClick={handleStart}>Start Tracing</Button>
</div>
this is my code but it doesnt seem to work as intended.Any help is much appreciated.
PS if you have any queries plz lemme know
You can use some Konva API to work with the path and get points on it.
useEffect(() => {
if (!check) {
return;
}
var node = ref.current;
// generate path from points
let data = coords
.map(([x, y], index) => {
if (index === 0) {
return `M ${x} ${y}`;
}
return `L ${x} ${y}`;
})
.join(" ");
const firstPoint = coords[0];
data += ` L ${firstPoint[0]} ${firstPoint[1]}`;
const path = new Konva.Path({
data
});
var anim = new Konva.Animation(function (frame) {
const length = path.getLength();
const delta = ((frame.time / 2000) % 1) * length;
const point = path.getPointAtLength(delta);
if (point) {
node.position(point);
}
}, node.getLayer());
anim?.start();
return () => {
anim?.stop();
path.destroy();
};
}, [check, i]);
https://codesandbox.io/s/react-konva-follow-path-mwd2w

Bubble Sort Visualizer problem with resizing and pressing button

I'm making Bubble Sort visualizer in React.
I've already done it and it's working, but what i want is that it is responsive so i am making that number of bars would shrink, i am doing it by dividing width and 14, because width of one bar is 8px and margin-right is 6px, but when i click button it wont work until i resize it, when i resize it then it will work
Here is my component SortingVisualization.js
import React, { Component } from "react";
import bubbleSort from "../algorithms/bubbleSort";
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
class SortingVisualizer extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
numberOfBars: 100,
widthOfBars: 8,
width: 0,
height: 0,
};
this.bubbleSortImp = this.bubbleSortImp.bind(this);
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
this.updateNumberOfBars = this.updateNumberOfBars.bind(this);
this.randomArray = this.randomArray.bind(this);
}
componentDidMount() {
this.updateWindowDimensions();
window.addEventListener("resize", this.updateWindowDimensions);
this.updateNumberOfBars();
window.addEventListener("resize", this.updateNumberOfBars);
this.randomArray();
window.addEventListener("resize", this.randomArray);
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateWindowDimensions);
window.removeEventListener("resize", this.updateNumberOfBars);
window.removeEventListener("resize", this.randomArray);
}
updateWindowDimensions() {
this.setState({ width: window.innerWidth, height: window.innerHeight });
}
updateNumberOfBars() {
let num = Math.floor(this.state.width / 15);
this.setState({ numberOfBars: num });
}
randomArray() {
let arr = [];
for (let i = 0; i < this.state.numberOfBars; i++) {
arr.push(this.randomNumber());
}
this.setState({ list: [...arr] });
}
randomNumber() {
let randomIndex = Math.floor(Math.random() * 100) + 1;
return randomIndex;
}
async bubbleSortImp(e) {
e.preventDefault();
let arr = this.state.list;
let len = this.state.list.length;
for (let i = 0; i < this.state.numberOfBars; i++) {
await sleep(50);
bubbleSort(arr, 0, len - 1);
this.setState({ list: [...arr] });
}
}
render() {
console.log(this.state.numberOfBars);
console.log(this.state.width);
return (
<>
<div className="sortingVisualizer">
{this.state.list.map((number, index) => (
<div
key={index}
style={{
height: `${number}` * 5,
width: this.state.widthOfBars,
}}
className="visualize"
></div>
))}
</div>
<div className="buttons">
<button className="btn" onClick={this.bubbleSortImp}>
Bubble Sort
</button>
</div>
</>
);
}
}
export default SortingVisualizer;
Here is my bubbleSort.js
let i = 0;
let j = 0;
const bubbleSort = (arr) => {
if (i < arr.length) {
for (let j = 0; j < arr.length - i - 1; j++) {
let a = arr[j];
let b = arr[j + 1];
if (a > b) {
swap(arr, j, j + 1);
}
}
}
i++;
};
const swap = (arr, a, b) => {
let temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
};
export default bubbleSort;
Here is video what is happening
https://streamable.com/0kk5yt
Here is GitHub Repo
https://github.com/sk0le/sorting-visualization
I found few issues in your implementation and modified the code accordingly. Please refer the below component code and the helper bubbleSort code as well. Hope this helps in resolving your issue.
Initially the sorting was not working because in componentDidMount you were setting the numberOfBars using the computed width but by that time the width didn't get updated in the state, hence the default value is 0. This is making numberOfBars to 0.
And in the utility method, sorting is not happening once the i >= array.lenth as the value is not reset to 0. Found these issues and updated the code accordingly.
Below is the updated code for SortingVisualizer,
//SortingVisualizer.js
import React, { Component } from "react";
import bubbleSort from "../algorithms/bubbleSort";
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
class SortingVisualizer extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
numberOfBars: 100,
widthOfBars: 8,
width: window.innerWidth,
height: window.innerHeight
};
this.bubbleSortImp = this.bubbleSortImp.bind(this);
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
this.randomArray = this.randomArray.bind(this);
}
getDerivedStateFromProps = (nextProps, prevState) => {
if (
prevState.width !== window.innerWidth ||
prevState.height !== window.innerHeight
) {
return {
width: window.innerWidth,
height: window.innerHeight
};
}
};
componentDidMount() {
this.updateWindowDimensions();
window.addEventListener("resize", this.updateWindowDimensions);
this.randomArray();
window.addEventListener("resize", this.randomArray);
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateWindowDimensions);
window.removeEventListener("resize", this.randomArray);
}
updateWindowDimensions() {
const width = window.innerWidth;
let num = Math.floor(width / 15);
this.setState(() => ({
width,
height: window.innerHeight,
numberOfBars: num
}));
}
randomArray() {
let arr = [];
for (let i = 0; i < this.state.numberOfBars; i++) {
arr.push(this.randomNumber());
}
this.setState(() => ({ list: [...arr] }));
}
randomNumber() {
let randomIndex = Math.floor(Math.random() * 100) + 1;
return randomIndex;
}
async bubbleSortImp(e) {
e.preventDefault();
let arr = this.state.list;
let len = this.state.list.length;
for (let i = 0; i < this.state.numberOfBars; i++) {
await sleep(50);
bubbleSort(arr, 0, len - 1);
this.setState(() => ({ list: [...arr] }));
}
}
render() {
console.log(this.state.numberOfBars);
console.log(this.state.width);
return (
<>
<div className="sortingVisualizer">
{this.state.list.map((number, index) => (
<div
key={index}
style={{
height: `${number}` * 5,
width: this.state.widthOfBars
}}
className="visualize"
></div>
))}
</div>
<div className="buttons">
<button className="btn" onClick={this.bubbleSortImp}>
Bubble Sort
</button>
</div>
</>
);
}
}
export default SortingVisualizer;
Below is the updated code for the utility bubbleSort
let i = 0;
let j = 0;
const bubbleSort = arr => {
if (i < arr.length) {
for (let j = 0; j < arr.length - i - 1; j++) {
let a = arr[j];
let b = arr[j + 1];
if (a > b) {
swap(arr, j, j + 1);
}
}
} else {
i = 0;
return;
}
i++;
};
const swap = (arr, a, b) => {
let temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
};
export default bubbleSort;

Error while calculating index value from props React (works when hardcoded)

I am using this to create a 3D interactive view for a product: https://github.com/aldrinc/React360. The code in question is:
import React, { Component } from "react";
import "./React360.css";
// You can play with this to adjust the sensitivity
// higher values make mouse less sensitive
const pixelsPerDegree = 3;
class React360 extends Component {
static defaultProps = { dir: 'awair-360', numImages: 55 };
state = {
dragging: false,
imageIndex: 0,
dragStartIndex: 0
};
componentDidMount = () => {
document.addEventListener("mousemove", this.handleMouseMove, false);
document.addEventListener("mouseup", this.handleMouseUp, false);
};
componentWillUnmount = () => {
document.removeEventListener("mousemove", this.handleMouseMove, false);
document.removeEventListener("mouseup", this.handleMouseUp, false);
};
handleMouseDown = e => {
e.persist();
this.setState(state => ({
dragging: true,
dragStart: e.screenX,
dragStartIndex: state.imageIndex
}));
};
handleMouseUp = () => {
this.setState({ dragging: false });
};
updateImageIndex = currentPosition => {
let numImages = this.props.numImages;
const pixelsPerImage = pixelsPerDegree * (360 / numImages);
const { dragStart, imageIndex, dragStartIndex } = this.state;
// pixels moved
let dx = (currentPosition - dragStart) / pixelsPerImage;
let index = Math.floor(dx) % numImages;
if (index < 0) {
index = numImages + index - 1;
}
index = (index + dragStartIndex) % numImages;
// console.log(index, dragStartIndex, numImages)
if (index !== imageIndex) {
this.setState({ imageIndex: index });
}
};
handleMouseMove = e => {
if (this.state.dragging) {
this.updateImageIndex(e.screenX);
}
};
preventDragHandler = e => {
e.preventDefault();
};
renderImage = () => {
const { imageIndex } = this.state;
if (isNaN(imageIndex)) {
this.setState({imageIndex: 0})
return
}
return (
<div className="react360">
<img
className="react-360-img"
alt=""
src={require(`./${this.props.dir}/${imageIndex}.jpg`)}
/>
</div>
);
};
render = () => {
return (
<div
className="react-360-img"
onMouseDown={this.handleMouseDown}
onDragStart={this.preventDragHandler}
>
{this.renderImage()}
</div>
);
};
}
export default React360;
I am running into an issue where hardcoding the variable for the number of images (numImages) results in proper function but when I set the number of images as a prop let numImages = this.props.numImages; my image index sometimes goes to NaN. I've made a hacky workaround by setting the imageIndex state to 0 if it is NaN but I would like to resolve this issue correctly by understanding what exactly is different with setting a variable using props vs hardcoding.

Resources