0

creating a span element which moves throughout the day, depending on the current time that element should be x% down of it's parent div.

snippet of relevant code:

const [timePercentage, setTimePercentage] = useState(timeToPercentage());
useEffect(() => {
    const interval = setInterval(() => {
        setTimePercentage(timeToPercentage());
    }, 60000);
    clearInterval(interval);
}, [time]);

tsx:

return(
<div className="relative grid flex-1 mt-2 text-sm">
        <span className={`w-full h-[.5px] bg-red-600 absolute top-[${timePercentage}%]`} />
</div>
)

the issue is react is not acknowledging this as a percentage. using chrome's inspector I am able to see the percentage ex. top-[50%] but the span does not move. If I were to manually change state to 50 Ex.( const [timePercentage, setTimePercentage] = useState(50) ). it would work. but timePercentage type if also a number.

helper functions (TS):

function getTime(): [number, number] {
const time = new Date();
const hours = time.getHours();
const mins = time.getMinutes();
return [hours, mins];
}

function timeToPercentage(): number {
const [hours, mins] = getTime();
const minsPercentage = mins / 60;
return ((hours + minsPercentage) / 24) * 100;
}
2
  • 1
    Use style attribute instead. Otherwise you have to safelist every possible top class Commented Sep 30, 2022 at 16:35
  • yea, that is the best option
    – Lee
    Commented Sep 30, 2022 at 17:11

2 Answers 2

1

There is an issue with your case. You should not pass data to class like that: top-[${timePercentage}%], because TailwindCSS will not handle this type of dynamic classes.

I think, that the way to solve this issue is to return in timeToPercntage() a className, i. e. return "top-${((hours + minsPercentage) / 24) * 100}".

Explanation in Docs

0

you can set dynamic nextjs value like const percent = v_question?.percent;

style={{width: percent + '%'}}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.