Home > Software design >  Using arbitrary runtime strings for Tailwind CSS class positioning
Using arbitrary runtime strings for Tailwind CSS class positioning

Time:12-17

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.

CodePudding user response:

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>
    )
}
  • Related