There are 2 ways of updating the value of currentPercentage
.
1.Scrolling
2.Click the button to update the percentage
For (1), I use react-scroll-percentage
library to get the percentage.
For (2), I create 2 buttons to update the value of currentPercentage
I want to set the percentage of currentPercentage
dynamically but I can’t find a way to handle it.
App.js
import "./styles.css";
import { useScrollPercentage } from "react-scroll-percentage";
import { useState } from "react";
export default function App() {
const [ref, percentage] = useScrollPercentage({
threshold: 0
});
// how to set the value of currentPercentage to percentage, while I can change the percentage by button
const [currentPercentage, setCurrentPercentage] = useState(0);
const onBtnClick = (num) => {
setCurrentPercentage(num);
};
return (
<div className="App" ref={ref}>
<button
onClick={() => {
onBtnClick(50);
}}
>
Change to 50%
</button>
<button
onClick={() => {
onBtnClick(100);
}}
>
Change to 100%
</button>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
<h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
</div>
);
}
Codesandbox
https://codesandbox.io/s/still-brook-hqb92?file=/src/App.js:0-2242