2

How can I specify a div's position from runtime data? Should I use some hook to set the className string? I find a lot of the time it's async issues that cause this kind of problem.

Anyway I was hoping someone could point me in the right direction, it's possible what I want to do isn't even supported by tailwind:

{timeRecord.clockedTimes.map((time, index) => {
         let date = new Date(time.start);
         let topOffset = getTopOffset(date).toFixed(4);
         let stringOffset = `top-[${topOffset}%]`;
         let className = "absolute " +stringOffset+" outline outline-red-400 w-1/2 left-1/2";
                
                
         return (
                  <div className={className} >
                     {stringOffset}
                  </div>
         )
})}

If I copy the text displayed inside the div by rendering the stringOffset from within the div and remove the composition of the className and just make it a static string with the runtime data copy and pasted it set's the right position.

2

1 Answer 1

1

Tailwind isn't built dynamically upon render. If you know what the value is before you compile you can include it or us something like cx to append a className, but you'll have to style in this case, you may need to play with the style prop a bit:

interface getTopOffsetProps {
    timeDate: Date
}

const getTopOffset = ({ timeDate }: getTopOffsetProps) => {
    return timeDate
}

interface ClockedTimes {
    time: string
}

const ChildComponent = ({ time }: ClockedTimes) => {
    const date = new Date(time)
    const stringOffsetStyle = `${getTopOffset({ timeDate: date })}`

    return (
        <div className="absolute outline outline-red-400 w-1/2 left-1/2" style={{ top: stringOffsetStyle }}>
            {stringOffset}
        </div>
    )
}

interface ParentComponentProps {
    timeRecord: string[]
}

const ParentComponent = ({ timeRecord }: ParentComponentProps) => {
    return (
        <div>

            {timeRecord.map((time, index) => {
                <ChildComponent time={time} />
            })
        </div>
    )
}
Sign up to request clarification or add additional context in comments.

2 Comments

This won't work because tailwind will not include dynamic classes in the build
Good point, styling is probably the only way to go in this situation. I'll append my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.