"useRefs" variable an initial value of a div reference? - javascript

Im trying to build an audio progess bar with react hooks. I was following a tutorial with react class based components but got a little lost with refs.
How can I give my useRef variables an initial value of the div ref when the page loads?
As soon as I start playing then the I get an error saying cant read offsetwidth of null. Obviously timeline ref is null as it doesnt have an initial value. How can I connect it to the div with id of timeline in the useEffect hook?
const AudioPlayer = () => {
const url = "audio file";
const [audio] = useState(new Audio(url));
const [duration, setDuration] = useState(0);
const [currentTime, setCurrentTime] = useState(0)
let timelineRef = useRef()
let handleRef = useRef()
useEffect(() => {
audio.addEventListener('timeupdate', e => {
setDuration(e.target.duration);
setCurrentTime(e.target.currentTime)
let ratio = audio.currentTime / audio.duration;
let position = timelineRef.offsetWidth * ratio;
positionHandle(position);
})
}, [audio, setCurrentTime, setDuration]);
const mouseMove = (e) => {
positionHandle(e.pageX);
audio.currentTime = (e.pageX / timelineRef.offsetWidth) * audio.duration;
};
const mouseDown = (e) => {
window.addEventListener('mousemove', mouseMove);
window.addEventListener('mouseup', mouseUp);
};
const mouseUp = (e) => {
window.removeEventListener('mousemove', mouseMove);
window.removeEventListener('mouseup', mouseUp);
};
const positionHandle = (position) => {
let timelineWidth = timelineRef.offsetWidth - handleRef.offsetWidth;
let handleLeft = position - timelineRef.offsetLeft;
if (handleLeft >= 0 && handleLeft <= timelineWidth) {
handleRef.style.marginLeft = handleLeft + "px";
}
if (handleLeft < 0) {
handleRef.style.marginLeft = "0px";
}
if (handleLeft > timelineWidth) {
handleRef.style.marginLeft = timelineWidth + "px";
}
};
return (
<div>
<div id="timeline" ref={(timeline) => { timelineRef = timeline }}>
<div id="handle" onMouseDown={mouseDown} ref={(handle) => { handleRef = handle }} />
</div>
</div>
)
}

The useRef() hook returns a reference to an object, with the current property. The current property is the actual value useRef points to.
To use the reference, just set it on the element:
<div id="timeline" ref={timelineRef}>
<div id="handle" onMouseDown={mouseDown} ref={handleRef} />
And then to use it, you need to refer to the current property:
let position = current.timelineRef.offsetWidth * ratio;
And positionHandle - you shouldn't actually set styles on elements in React in this way. Use the setState() hook, and set the style using JSX.
const positionHandle = (position) => {
let timelineWidth = timelineRef.current.offsetWidth - handleRef.current.offsetWidth;
let handleLeft = position - timelineRef.current.offsetLeft;
if (handleLeft >= 0 && handleLeft <= timelineWidth) {
handleRef.current.style.marginLeft = handleLeft + "px";
}
if (handleLeft < 0) {
handleRef.current.style.marginLeft = "0px";
}
if (handleLeft > timelineWidth) {
handleRef.current.style.marginLeft = timelineWidth + "px";
}
};
In addition, the ref can be also used for other values, such as the new Audio(url), and be extracted from the current property:
const { current: audio } = useRef(new Audio(url));

Related

How to test useRef and functions defined inside of useEffect (using Jest)?

I would like to ask for help to improve my skills about test and code quality.
I read a ton of guides and docs and I was not able to find an example of how to do a better code or test in a clean way.
My component has two useRef and it add some listeners to allow the user resize the div element. it works as expected! But I wish to ensure (by tests) that functions onMouseDownRightResize and onMouseMoveRightResize adjust the component using the correct data.
Could someone please show me:
how to test onMouseDownRightResize or onMouseMoveRightResize once the were defined inside the useEffect?
how to test if ref.current is null once he it is inside of the useEffect
Here is my code and a link to a code pen
https://codepen.io/getjv/pen/LYBZPrp
const { useState, useEffect, useRef } = React;
const App = () => {
const ref = useRef(null);
const refRight = useRef(null);
useEffect(() => {
const resizeableEle = ref.current;
if (!resizeableEle) {
return;
}
const styles = window.getComputedStyle(ref.current);
let width = parseInt(styles.width, 10);
let x = 0;
const onMouseMoveRightResize = (event) => {
const dx = event.clientX - x;
x = event.clientX;
width = width + dx;
resizeableEle.style.width = `${width}px`;
};
const onMouseUpRightResize = (event) => {
document.removeEventListener("mousemove", onMouseMoveRightResize);
};
const onMouseDownRightResize = (event) => {
x = event.clientX;
resizeableEle.style.left = styles.left;
resizeableEle.style.right = "";
document.addEventListener("mousemove", onMouseMoveRightResize);
document.addEventListener("mouseup", onMouseUpRightResize);
};
const resizerRight = refRight.current;
if (!resizerRight) {
return;
}
resizerRight.addEventListener("mousedown", onMouseDownRightResize);
return () => {
resizerRight.removeEventListener(
"mousedown",
onMouseDownRightResize
);
};
}, []);
return (
<div className="App">
<div ref={ref} className="flex w-40 border border-red-500 m-5">
<div className="w-full">move the green -> </div>
<div
ref={refRight}
className="bg-green-500 w-2 cursor-col-resize"
></div>
</div>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("app"));

Building an editable tree of connected nodes in React

I am trying to build a tree in React wherein one can add nodes and connect them and move them around, like the included picture.
How does one go about doing this?
I am working with create-react-app
I have tried all sorts of things but I keep having trouble with event.clientX/event.pageX, it keeps giving me random values which results in the nodes flickering.
To me it makes most sense to have the node-moving functionality on the level of the tree but that approach gives this flickering problem.
How to prevent event.clientX from giving me random values?
The problem i normally have is the flickering of the sort in this codepen:
https://codesandbox.io/s/delicate-http-nnzx4?file=/src/App.js
(click and drag)
I have tried a number of things and the only way it works (altough buggy) is the way below where the node-moving functionality is on the level of the node:
import React, {useState,useEffect,useRef, useCallback, createRef} from 'react';
import "./PrinciplesTree.css"
function Line(props){
function clickhandler(e){
e.stopPropagation()
props.deletenodeconnection(props.firstpoint.node_number,props.secondpoint.node_number)
}
const firstpoint = props.firstpoint
const secondpoint = props.secondpoint
var x1 = firstpoint.anchor_pos.anchorposx
var y1 = firstpoint.anchor_pos.anchorposy
var x2 = secondpoint.anchor_pos.anchorposx
var y2 = secondpoint.anchor_pos.anchorposy
if (x2 < x1) {
var tmp;
tmp = x2 ; x2 = x1 ; x1 = tmp;
tmp = y2 ; y2 = y1 ; y1 = tmp;
}
var lineLength = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
var m = (y2 - y1) / (x2 - x1);
var degree = Math.atan(m) * 180 / Math.PI;
const divstyle = {transformOrigin: 'top left', transform: 'rotate(' + degree + 'deg)', width: lineLength + "px", height: 1 + 'px', background: 'black',
position: 'absolute', top: y1 + "px", left: x1 + "px"}
return <div className='line' style={divstyle} onClick={clickhandler}></div>
}
function Node(props) {
const [val, setval] = useState("Enter Principle");
const node_number = props.nodeN
const node_width = '150px'
const anchorel = useRef(null)
var offsetx = 0
var offsety = 0
let parentleft = 0
let parentright = 0
let parenttop = 0
let parentbottom = 0
const onclick = e =>{
e.stopPropagation();
const anchorpositionX = anchorel.current.getBoundingClientRect().left
const anchorpositionY = anchorel.current.getBoundingClientRect().top
const parentleft = e.target.parentElement.getBoundingClientRect().left
const parenttop = e.target.parentElement.getBoundingClientRect().top
const anchorpos = {anchorposx: anchorpositionX - parentleft, anchorposy: anchorpositionY - parenttop}
props.connectnode.current(node_number,anchorpos)
}
const movehandler = e => {
var newvalx = e.clientX-parentleft-offsetx
var newvaly = e.clientY-parenttop-offsety
if(((parentleft + newvalx) < parentright + 5 && (parentleft + newvalx) > parentleft - 5) &&
(parenttop + newvaly > parenttop - 5 && parenttop + newvaly < parentbottom + 5)){
props.updatenode(node_number,newvalx,newvaly)
}
}
const addmovehandler = e => {
const parent = e.target.parentElement
parentleft = parent.getBoundingClientRect().left
parentright = parent.getBoundingClientRect().right
parenttop = parent.getBoundingClientRect().top
parentbottom = parent.getBoundingClientRect().bottom
offsetx = e.clientX - e.target.getBoundingClientRect().left
offsety = e.clientY - e.target.getBoundingClientRect().top
document.addEventListener('mouseover',movehandler)
}
const removenodehandler = e =>{
const parent = e.target.parentElement
document.removeEventListener('mouseover',movehandler)
}
function edit(e){
e.stopPropagation();
if(e.key === 'Enter'){
setval(e.target.value)
}
}
return <div className='node' style = {{left: props.posX, top: props.posY, width: node_width}} onMouseDown={addmovehandler} onMouseUp = {removenodehandler} onClick = {onclick}>
<div className='anchor' ref={anchorel}></div>
<textarea className = 'principle' name = {val} onKeyDown={edit} placeholder = {val}></textarea>
<img src="cross.png" className='Cross' onClick={(e) => props.deletenode(node_number)}></img>
</div>
}
function PrinciplesTree() {
const [nodes, setnodes] = useState([]);
const [connectednodes, setconnectednodes] = useState([]);
const nodetoconnect = useRef(null)
const connectnoderef = useRef()
useEffect(() => {
setnodes([{key: 1, nodeN: 1, posX: 0, posY: 0, deletenode: deletenode, connectnode: connectnoderef, updatenode: updatenode}])
},[]);
const connectnode = (nodeN,anchorpos) => {
if(nodetoconnect.current == null){
nodetoconnect.current = {node_number: nodeN, anchor_pos: anchorpos}
}else if(nodetoconnect.current != null && nodeN != nodetoconnect.current.node_number )
{
const node_to_add = nodetoconnect.current
const firstnodenumber = nodetoconnect.current.node_number
const secondnodenumber = nodeN
var foundpair = false
connectednodes.forEach(connectednode => {
const firstnode = connectednode.first.node_number
const secondnode = connectednode.second.node_number
if((firstnode == firstnodenumber && secondnode == secondnodenumber) || (firstnode == secondnodenumber && secondnode == firstnodenumber)){
foundpair = true
}
})
const newnodetoconnect = {first: node_to_add, second: {node_number: nodeN, anchor_pos: anchorpos}}
if(foundpair == false){
setconnectednodes(connectednodes => [...connectednodes,newnodetoconnect])
}
nodetoconnect.current = null
}
}
connectnoderef.current = connectnode
function deletenodeconnection(node1,node2){
setconnectednodes(prevconnectednodes => {
return prevconnectednodes.filter(connectednodes => !(connectednodes.first.node_number == node1 && connectednodes.second.node_number == node2))
})
}
const deletenode = (NodeN) =>{
setnodes(prevnodes => {
return prevnodes.filter(node => node.nodeN !== NodeN)})
}
const updatenode = (NodeN,newposx,newposy)=> {
const updnode = {key: NodeN, nodeN: NodeN, posX: newposx, posY: newposy, deletenode: deletenode, connectnode: connectnoderef, updatenode: updatenode}
setnodes(nodes => (
nodes.map(node => {
if(node.nodeN == NodeN){
return updnode
}
else return node }
)))
}
function createnode(e){
var el = e.target
var posX=e.clientX-el.getBoundingClientRect().left
var posY=e.clientY-el.getBoundingClientRect().top
var newkey = 0;
nodes.forEach(node => {
if(node.key >= newkey){
newkey = parseInt(node.key) + 1
}
});
var newnode = {key: newkey, nodeN: nodes.length + 1, posX: posX, posY: posY, deletenode: deletenode, connectnode: connectnoderef, updatenode: updatenode}
setnodes(nodes => [...nodes, newnode]);
}
return <div onClick={createnode} className='TreeCanvas'>
{connectednodes.map(connectednode=> <Line firstpoint = {connectednode.first} secondpoint = {connectednode.second} deletenodeconnection={deletenodeconnection}/>)}
{nodes.map(node => <Node key = {node.key} nodeN = {node.nodeN} posX = {node.posX} posY = {node.posY} deletenode = {node.deletenode}
connectnode = {node.connectnode} updatenode = {node.updatenode}/>)}
</div>
}
export default PrinciplesTree;
Someone with the handle #wordswithjosh helped me a great deal on Reddit so I want to post his answer here for any people who might have the same question in the future.
Gotcha - I've had some difficulty in the past getting draggable components to update smoothly. Where I've found the most success is usually resisting the urge to use the onDrag or onMouseMove event in the component, instead just using the mouse movement event to remember the position of the cursor, and instead using requestAnimationFrame to actually visually move the component.
This seems like overkill at first, but when you want multiple components to visually update simultaneously, I've found that the most reliable pattern is something like this:
const TreeNode = () => {
const [originalLeft, setOriginalLeft] = useState(0); // very rarely is an initial value of 'undefined' desirable; this is one of those times
const [originalTop, setOriginalTop] = useState(0);
const [left, setLeft] = useState();
const [top, setTop] = useState();
const [originalMouseX, setOriginalMouseX] = useState(0);
const [originalMouseY, setOriginalMouseY] = useState(0);
const [newMouseX, setNewMouseX] = useState(0);
const [newMouseY, setNewMouseY] = useState(0);
const mutableFrameRef = useRef({ paused: true, lastFrame: null });
const selfRef = useRef(null);
const loop = () => {
// this shouldn't be necessary, but it's a failsafe to prevent
// runaway recursive function behavior I've experienced in the
// past when working with rAF
if (mutableFrameRef.current.paused) return;
// on every frame, set the new position of the div to its
// previous position plus the current offset of the mouse
setLeft(originalLeft + (newMouseX - originalMouseX));
setTop(originalY + (newMouseY - originalMouseY));
// this IS necessary, and is the default way of keeping a reference
// to the handle used to cancel the last requested frame
mutableFrameRef.current.lastFrame = requestAnimationFrame(loop);
};
// not destructuring these params for performance
const handleMouseMove = e => {
setNewMouseX(e.clientX);
setNewMouseY(e.clientY);
};
const handleMouseDown = ({ clientX, clientY }) => {
setOriginalMouseX(clientX);
setOriginalMouseY(clientY);
setNewMouseX(clientX);
setNewMouseY(clientY);
document.addEventListener('mousemove', handleMouseMove);
};
const handleMouseUp = ({ clientX, clientY }) => {
mutableFrameRef.paused = true;
cancelAnimationFrame(mutableFrameRef.current.lastFrame);
// one more time just to be sure
setLeft(originalLeft + (newMouseX - originalMouseX));
setTop(originalY + (newMouseY - originalMouseY));
document.removeEventListener('mousemove', handleMouseMove);
};
useEffect(() => {
// default both our original and "live" top left corner coordinates to what they are on first paint
const { x, y } = selfRef.current.getBoundingClientRect();
setOriginalLeft(x);
setOriginalTop(y);
setLeft(x);
setTop(y);
}, []);
return (
<div
ref={selfRef}
className='tree-node'
style={{
top,
left
}}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
draggable
>
// text stuff, tree node contents, etc - not relevant
</div>
);
};
Full disclosure, I haven't tested this exact config, I kinda wrote it live 😅 but I've used almost this exact pattern in the past, and I think you can get the idea - the main thing is that we only ask the browser to re-draw the div on every monitor refresh, which can drastically improve performance and help eliminate odd flickering.
You could, of course, avoid redrawing the div altogether by simply using the onDrag event to update the saved cursor position, and then update the actual drawn div location with onDragEnd, but I imagine the sort of "ghosting" behavior exhibited during the builtin HTML drag is not what you're looking for, and would not provide nearly as pretty of a user experience.

Scroll Sequence with .png image work weird

So I working on my project and I want to make some section kind of Apple Scroll Sequence.
But when I convert the image sequence to .PNG, it's awful :(
So, here's the image lookalike when I scroll the section. It's like shadowing / emm I don't know what it is haha.
Here's my codes:
<div class="intermezo-sequence">
<div class="sticky-element">
<div class="sequence-element">
<canvas id="intermezo_canvas"></canvas>
</div>
</div>
</div>
const canvas = document.querySelector('#hero_canvas')
const ctx = canvas.getContext('2d')
const heroSequence = document.querySelector('.hero-sequence')
const images = []
var sequence1 = <?= json_encode($sequence1) ?>;
sequence1.sort();
const frameCount = sequence1.length; // biar dinamis total nya
const prepareImages = () => {
for (var i = 0; i < frameCount; i++) {
// console.log(sequence1[i]);
const image = new Image()
// image.src = `./assets/images/studycase/sequence/${i}.jpg`
canvas.width = 1928;
canvas.height = 1000;
image.src = sequence1[i];
images.push(image)
if (i === 0) {
images[i].onload = () => drawImage1(0)
}
}
}
const drawImage1 = frameIndex => {
ctx.drawImage(images[frameIndex], 0, 0)
}
prepareImages()
const heroSection = document.getElementById("heroSection");
window.addEventListener('scroll', () => {
const scrollTop = document.documentElement.scrollTop - heroSection.offsetTop
const maxScrollTop = heroSequence.scrollHeight - window.innerHeight
const scrollFraction = scrollTop / maxScrollTop
const frameIndex = Math.max(0, Math.min(frameCount - 1, Math.ceil(scrollFraction * frameCount)))
images[frameIndex].onload = () => drawImage1(frameIndex)
requestAnimationFrame(() => drawImage1(frameIndex))
})
Is there anything that I should add to the logic? Thanks!

How to render the actual value of the scroll percentage?

I have this piece of code
import React from 'react'
const App = () => {
function getScrollPercent() {
var h = document.documentElement,
b = document.body,
st = 'scrollTop',
sh = 'scrollHeight';
var scrollPercent = Math.round((h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100);
//get the percentage of scroll
return (isNaN(scrollPercent) ? '' : scrollPercent)
}
return (
<p>{`${getScrollPercent()}%`}</p>
)
the problem is when I scroll the scrollPercent doesn't refresh in real time but only when the scroll stop, so scrollPercent can pass from 0% to 100% and not display all the numbers between 0 and 100, so the question is how can I modify my piece of code to display the actual value of scrollPercent even when I scroll
You will need to use a useEffect to add an event listener that will listen for the scroll event. Then, you can register a function that will re-calculate the scroll position when the user scrolls up or down the page.
import React, { useEffect, useState } from "react";
function getScrollPercent() {
var h = document.documentElement,
b = document.body,
st = "scrollTop",
sh = "scrollHeight";
var scrollPercent = Math.round(
((h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight)) * 100
);
//get the percentage of scroll
return isNaN(scrollPercent) ? "" : scrollPercent;
}
const App = () => {
// this represents the current calculated scroll percentage
// maybe initialize this to something other than empty string
const [scrollPercentage, setScrollPercentage] = useState("");
useEffect(() => {
function handleScroll() {
const newScrollPercentage = getScrollPercent();
// calculate and set the new scroll percentage
setScrollPercentage(newScrollPercentage);
}
window.addEventListener("scroll", handleScroll, true);
// clean up event listener when component unmounts
return () => {
window.removeEventListener('scroll', handleScroll, true);
}
}, []);
// this contains extra styling to demo, so that you can see the
// scroll value change when scrolling, probably remove these style props
return (
<div style={{ height: "3000px" }}>
<p style={{ position: "fixed" }}>{`${scrollPercentage}%`}</p>
</div>
);
};
export default App;
Codesandbox Link to example: Codesandbox
You need to use window.addEventListener to reach what you want.
import React from "react";
const App = () => {
const [scroll, setScroll] = React.useState("");
function getScrollPercent() {
var h = document.documentElement,
b = document.body,
st = "scrollTop",
sh = "scrollHeight";
var scrollPercent = Math.round(
((h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight)) * 100
);
setScroll(isNaN(scrollPercent) ? "" : scrollPercent);
}
React.useEffect(() => {
window.addEventListener("scroll", getScrollPercent);
return () => {
window.removeEventListener("scroll", getScrollPercent);
};
}, []);
return (
<div style={{ height: "1000px" }}>
<p style={{ position: "fixed" }}>{`${scroll}%`}</p>
</div>
);
};
export default App;
Codesanbox Link: https://codesandbox.io/s/unruffled-field-3l3z8?file=/src/App.js:0-664

How to correctly wait on state to update/render instead of using a delay/timeout function?

I will attempt to keep this brief, but I am not 100% sure of the correct method of achieving what I am aiming for. I have been thrown in the deep end with React with not much training, so I have most likely been going about most of this component incorrectly, a point in the right direction will definitely help, I don't really expect for someone to completely redo my component for me as it's quite long.
I have a navigation bar SubNav, that finds the currently active item based upon the url/path, this will then move an underline element that inherits the width of the active element. To do this, I find the position of the active item and position accordingly. The same goes for when a user hovers over another navigation item, or when the window resizes it adjusts the position accordingly.
I also have it when at lower resolutions, when the nav gets cut off to have arrows appear to scroll left/right on the navigation to view all navigation items.
Also, if on a lower resolution and the currently active navigation item is off screen, the navigation will scroll to that item and then position the underline correctly.
This, currently works as I have it in my component, this issue is, I don't believe I have done this correctly, I am using a lodash function delay to delay at certain points (I guess to get the correct position of certain navigation items, as it isn't correct at the time of the functions call), which I feel is not the way to go. This is all based on how fast the page loads etc and will not be the same for each user.
_.delay(
() => {
setSizes(getSizes()),
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
400,
setArrowStyle(styling)
);
Without using the delay, the values coming back from my state are incorrect as they haven't been set yet.
My question is, how do I go about this correctly? I know my code below is a bit of a read but I have provided a CODESANBOX to play about with.
I have 3 main functions, that all sort of rely on one another:
getPostion()
This function finds the active navigation item, checks if it's within the viewport, if it is not, then it changes the left position of the navigation so it's the leftmost navigation item on the screen, and via setSizes(getSizes()) moves the underline directly underneath.
getSizes()
This is called as an argument within setSizes to update the sizes state, which returns the left and right boundaries of all navigation items
getUnderlineStyle()
This is called as an argument within setUnderLineStyle within the getSizes() function to update the position of the underline object in relation to the position of active navigation item grabbed from the sizes state, but I have to pass the sizesObj as an argument in setSizes as the state has not been set. I think this is where my confusion began, I think I was under the impression, that when I set the state, I could then access it. So, I started using delay to combat.
Below is my whole Component, but can be seen working in CODESANBOX
import React, { useEffect, useState, useRef } from "react";
import _ from "lodash";
import { Link, Route } from "react-router-dom";
import "../../scss/partials/_subnav.scss";
const SubNav = props => {
const subNavLinks = [
{
section: "Link One",
path: "link1"
},
{
section: "Link Two",
path: "link2"
},
{
section: "Link Three",
path: "link3"
},
{
section: "Link Four",
path: "link4"
},
{
section: "Link Five",
path: "link5"
},
{
section: "Link Six",
path: "link6"
},
{
section: "Link Seven",
path: "link7"
},
{
section: "Link Eight",
path: "link8"
}
];
const currentPath =
props.location.pathname === "/"
? "link1"
: props.location.pathname.replace(/\//g, "");
const [useArrows, setUseArrows] = useState(false);
const [rightArrow, updateRightArrow] = useState(false);
const [leftArrow, updateLeftArrow] = useState(false);
const [sizes, setSizes] = useState({});
const [underLineStyle, setUnderLineStyle] = useState({});
const [arrowStyle, setArrowStyle] = useState({});
const [activePath, setActivePath] = useState(currentPath);
const subNavRef = useRef("");
const subNavListRef = useRef("");
const arrowRightRef = useRef("");
const arrowLeftRef = useRef("");
let elsRef = Array.from({ length: subNavLinks.length }, () => useRef(null));
useEffect(
() => {
const reposition = getPosition();
subNavArrows(window.innerWidth);
if (!reposition) {
setSizes(getSizes());
}
window.addEventListener(
"resize",
_.debounce(() => subNavArrows(window.innerWidth))
);
window.addEventListener("resize", () => setSizes(getSizes()));
},
[props]
);
const getPosition = () => {
const activeItem = findActiveItem();
const itemHidden = findItemInView(activeItem);
if (itemHidden) {
const activeItemBounds = elsRef[
activeItem
].current.getBoundingClientRect();
const currentPos = subNavListRef.current.getBoundingClientRect().left;
const arrowWidth =
arrowLeftRef.current !== "" && arrowLeftRef.current !== null
? arrowLeftRef.current.getBoundingClientRect().width
: arrowRightRef.current !== "" && arrowRightRef.current !== null
? arrowRightRef.current.getBoundingClientRect().width
: 30;
const activeItemPos =
activeItemBounds.left * -1 + arrowWidth + currentPos;
const styling = {
left: `${activeItemPos}px`
};
_.delay(
() => {
setSizes(getSizes()),
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
400,
setArrowStyle(styling)
);
return true;
}
return false;
};
const findActiveItem = () => {
let activeItem;
subNavLinks.map((i, index) => {
const pathname = i.path;
if (pathname === currentPath) {
activeItem = index;
return true;
}
return false;
});
return activeItem;
};
const getSizes = () => {
const rootBounds = subNavRef.current.getBoundingClientRect();
const sizesObj = {};
Object.keys(elsRef).forEach(key => {
const item = subNavLinks[key].path;
const el = elsRef[key];
const bounds = el.current.getBoundingClientRect();
const left = bounds.left - rootBounds.left;
const right = rootBounds.right - bounds.right;
sizesObj[item] = { left, right };
});
setUnderLineStyle(getUnderlineStyle(sizesObj));
return sizesObj;
};
const getUnderlineStyle = (sizesObj, active) => {
sizesObj = sizesObj.length === 0 ? sizes : sizesObj;
active = active ? active : currentPath;
if (active == null || Object.keys(sizesObj).length === 0) {
return { left: "0", right: "100%" };
}
const size = sizesObj[active];
const styling = {
left: `${size.left}px`,
right: `${size.right}px`,
transition: `left 300ms, right 300ms`
};
return styling;
};
const subNavArrows = windowWidth => {
let totalSize = sizeOfList();
_.delay(
() => {
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
300,
setUseArrows(totalSize > windowWidth)
);
};
const sizeOfList = () => {
let totalSize = 0;
Object.keys(elsRef).forEach(key => {
const el = elsRef[key];
const bounds = el.current.getBoundingClientRect();
const width = bounds.width;
totalSize = totalSize + width;
});
return totalSize;
};
const onHover = active => {
setUnderLineStyle(getUnderlineStyle(sizes, active));
setActivePath(active);
};
const onHoverEnd = () => {
setUnderLineStyle(getUnderlineStyle(sizes, currentPath));
setActivePath(currentPath);
};
const scrollRight = () => {
const currentPos = subNavListRef.current.getBoundingClientRect().left;
const arrowWidth = arrowRightRef.current.getBoundingClientRect().width;
const subNavOffsetWidth = subNavRef.current.clientWidth;
let nextElPos;
for (let i = 0; i < elsRef.length; i++) {
const bounds = elsRef[i].current.getBoundingClientRect();
if (bounds.right > subNavOffsetWidth) {
nextElPos = bounds.left * -1 + arrowWidth + currentPos;
break;
}
}
const styling = {
left: `${nextElPos}px`
};
_.delay(
() => {
setSizes(getSizes()),
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
500,
setArrowStyle(styling)
);
};
const scrollLeft = () => {
const windowWidth = window.innerWidth;
// const lastItemInView = findLastItemInView();
const firstItemInView = findFirstItemInView();
let totalWidth = 0;
const hiddenEls = elsRef
.slice(0)
.reverse()
.filter((el, index) => {
const actualPos = elsRef.length - 1 - index;
if (actualPos >= firstItemInView) return false;
const elWidth = el.current.getBoundingClientRect().width;
const combinedWidth = elWidth + totalWidth;
if (combinedWidth > windowWidth) return false;
totalWidth = combinedWidth;
return true;
});
const targetEl = hiddenEls[hiddenEls.length - 1];
const currentPos = subNavListRef.current.getBoundingClientRect().left;
const arrowWidth = arrowLeftRef.current.getBoundingClientRect().width;
const isFirstEl =
targetEl.current.getBoundingClientRect().left * -1 + currentPos === 0;
const targetElPos = isFirstEl
? targetEl.current.getBoundingClientRect().left * -1 + currentPos
: targetEl.current.getBoundingClientRect().left * -1 +
arrowWidth +
currentPos;
const styling = {
left: `${targetElPos}px`
};
_.delay(
() => {
setSizes(getSizes()),
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
500,
setArrowStyle(styling)
);
};
const findItemInView = pos => {
const rect = elsRef[pos].current.getBoundingClientRect();
return !(
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= window.innerHeight &&
rect.right <= window.innerWidth
);
};
const findLastItemInView = () => {
let lastItem;
for (let i = 0; i < elsRef.length; i++) {
const isInView = !findItemInView(i);
if (isInView) {
lastItem = i;
}
}
return lastItem;
};
const findFirstItemInView = () => {
let firstItemInView;
for (let i = 0; i < elsRef.length; i++) {
const isInView = !findItemInView(i);
if (isInView) {
firstItemInView = i;
break;
}
}
return firstItemInView;
};
return (
<div
className={"SubNav" + (useArrows ? " SubNav--scroll" : "")}
ref={subNavRef}
>
<div className="SubNav-content">
<div className="SubNav-menu">
<nav className="SubNav-nav" role="navigation">
<ul ref={subNavListRef} style={arrowStyle}>
{subNavLinks.map((el, i) => (
<Route
key={i}
path="/:section?"
render={() => (
<li
ref={elsRef[i]}
onMouseEnter={() => onHover(el.path)}
onMouseLeave={() => onHoverEnd()}
>
<Link
className={
activePath === el.path
? "SubNav-item SubNav-itemActive"
: "SubNav-item"
}
to={"/" + el.path}
>
{el.section}
</Link>
</li>
)}
/>
))}
</ul>
</nav>
</div>
<div
key={"SubNav-underline"}
className="SubNav-underline"
style={underLineStyle}
/>
</div>
{leftArrow ? (
<div
className="SubNav-arrowLeft"
ref={arrowLeftRef}
onClick={scrollLeft}
/>
) : null}
{rightArrow ? (
<div
className="SubNav-arrowRight"
ref={arrowRightRef}
onClick={scrollRight}
/>
) : null}
</div>
);
};
export default SubNav;
You can make use of useLayoutEffect hook to determine whether the values have been updated and take an action. Since you want to determine whether all the values has been updated, you need to compare old and new values in useEffect. You can refer to the below post to know how to write a usePrevious custom hook
How to compare oldValues and newValues on React Hooks useEffect?
const oldData = usePrevious({ rightArrow, leftArrow, sizes});
useLayoutEffect(() => {
const {rightArrow: oldRightArrow, leftArrow: oldLeftArrow, sizes: oldSizes } = oldData;
if(oldRightArrow !== rightArrow && oldLeftArrow !== leftArrow and oldSizes !== sizes) {
setArrowStyle(styling)
}
}, [rightArrow, leftArrow, sizes])
I think the reason of your delay is necessary here since you calculate based on rectangles of the first and the last element which are affected when you click on button and do animation of scrolling 500ms. So as a result your calculation needs to wait for animation to be done. change the number of animation and delay you will see the relation.
the style I meant.
#include transition(all 500ms ease);
In short, I think what you are using is the right way as long as you have animations related to the calculation.
setState takes an optional second argument which is a callback that executes after the state has been updated and the component has been re-rendered.
Another option is the componentDidUpdate lifecycle method.

Categories

Resources