Employing random runtime strings for the placement of Tailwind CSS classes

Is there a way to define the position of a div using runtime data? Would setting the className string through some hook be the solution? I often encounter issues with asynchronous operations causing this type of problem.

I was hoping someone could guide me in the right direction, as it's possible that what I'm trying to achieve is not compatible with tailwind CSS:

{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 extract the text displayed inside the div by rendering the stringOffset from within and eliminate the construction of the className to make it a static string with the runtime data copied and pasted, it positions correctly.

Answer №1

When using Tailwind, keep in mind that it is not generated dynamically upon rendering. If you are aware of the value before compilation, you can include it directly or utilize a function like cx to add a className. However, if you need to style dynamically, you might have to experiment with the style prop:

interface OffsetProps {
    timeDate: Date
}

const calculateOffset = ({ timeDate }: OffsetProps) => {
    return timeDate;
}

interface TimeProps {
    time: string
}

const ChildComponent = ({ time }: TimeProps) => {
    const date = new Date(time);
    const stringOffsetStyle = `${calculateOffset({ timeDate: date })}`;

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

interface RecordsProps {
    timeRecord: string[]
}

const ParentComponent = ({ timeRecord }: RecordsProps) => {
    return (
        <div>
            {timeRecord.map((time, index) => {
                return <ChildComponent time={time} />;
            })}
        </div>
    )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message when testing Angular 6 ngrx store: Unable to retrieve ids from undefined variable

I'm currently in the process of testing a component that has received a Store injection. However, I am encountering an issue where the test is failing and displaying an error message: "Cannot read property 'ids' of undefined" Test: const ...

What data structure is used to store HTML elements in TypeScript?

Currently, I am dealing with a typescript variable that holds the outcome of a query on the DOM: let games = document.getElementsByTagname("game"); My uncertainty lies in identifying the appropriate type for the resulting array. Should I expect an array ...

Next.js Alert - The Google Maps JavaScript API is being utilized multiple times throughout this page

After following the instructions in the documentation to implement the react-places-autocomplete library, I encountered an error stating "You have included the Google Maps JavaScript API multiple times on this page" whenever there were 4-5 instances of the ...

Moving the scrollbar does not cause the div to scroll

While working on a webpage design, I encountered an issue with creating a header that includes a scrolling div element when the content overflows. You can view the code here. Within this code, there is a categories div featuring 'Home, News, Movies,.. ...

Exclusive workshop on concealing H1 header in Jumbotron

Trying to make a Jumbotron's height 100% of the user's browser window with a special class, but running into issues on mobile devices as a div within the jumbotron is covering up the headline. Any suggestions for a fix? Live link: HTML <di ...

Utilizing local storage, store and access user's preferred layout options through a click function

Exploring the realm of localstorage for the first time, I am considering its use to store a specific ID or CLASS from my css file. This stored information would then be utilized to render a selected layout (grid/list) in the user's browser upon their ...

Displaying a Leaflet marker on a map, yet it defaults to showing the placeholder for a broken image

Here is a preview: https://i.sstatic.net/vBTKM.png This is my code: Map.js //this snippet of code remained unchanged as I found it online and kept it for reference //to avoid redundant suggestions import L from 'leaflet'; delete L.Icon.Default ...

Creating a Blog Post with Pagination on Blogger

After creating pagination for 1 to 10 posts, I encountered an issue where clicking on page 1 or 2 does not show as the visited or active page. Any advice on how to fix this? Below is the CSS code: .post-pagination { margin: 100px auto; text-align ...

What is the best way to modify this state without altering the original array?

I am seeking guidance on how to avoid mutating state in a specific scenario: In my React Hooks setup, I have a TodoList component that displays a list of TodoItems. Each TodoItem can be clicked to trigger a function called toggle, which switches its compl ...

The Angular program is receiving significant data from the backend, causing the numbers to be presented in a disorganized manner within an

My Angular 7 application includes a service that fetches data from a WebApi utilizing EntityFramework to retrieve information. The issue arises when numeric fields with more than 18 digits are incorrectly displayed (e.g., the number 23434343434345353453,3 ...

Hovering over an image and trying to rotate it results in

Check out my rotating image example on hover in React here This effect utilizes scale(), rotate(), and transition properties to create an animated rotation when hovering over the parent element. Additionally, overflow: hidden is applied to the parent elem ...

The most effective method for updating the Material UI React theme during runtime

As a newcomer to React and Material UI, I am still grappling with the concept of composition over inheritance. Currently, my focus is on implementing the ability to switch between dark and light themes dynamically in a React application. Although I have ma ...

Exploring the capabilities of TypeScript in conjunction with the useRoute function on React Navigation version

When using useRoute, I am attempting to extract the parameters like this: const route = useRoute(); const { params } = route; const { id, name, } = params; Although everything is functioning correctly, the linter is pointing out that id and na ...

Transform OKTA Observable into a practical string variable

I'm currently in the process of developing a service in Angular 12 that retrieves a "User" object, with OKTA being used for authentication. My goal is to streamline the process. I can easily obtain the family name as an Observable using the following ...

What is the best way to simulate a library in jest?

Currently, I am attempting to simulate the file-type library within a jest test scenario. Within my javascript document, this particular library is utilized in the subsequent manner: import * as fileType from 'file-type'; .... const uploadedFil ...

Encountering issues with Prisma DB on the 13th attempt: Seed.ts failing to

Currently, I am in the process of developing a web application using Next 13. To handle my ORM, I have opted for Prisma and my Postgres database is being hosted on SupaBase. Following a recent Next 13 course update, I have reached the stage where I need to ...

What is the best way to conceal the arrow that is included with the datalist?

Recently, I began my journey in coding and encountered an issue with the arrow that appears along with the options in datalist. Here's a screenshot for reference: datalist arrow I attempted to solve this problem using the following code: input[type ...

Revamping the hyperlinks in my collapsible menu extension

Is there a way to modify the links in this accordion drop menu so that they lead to external HTML pages instead of specific areas on the same page? I've tried various methods but can't seem to achieve it without affecting the styles. Currently, i ...

The height of the first item in the navigation menu seems oddly disproportionate

I've been struggling for nearly an hour to make my navigation menu visually appealing. I'm utilizing Twitter Bootstrap's flat CSS menu. Oddly, the first item in the menu appears taller than all the other items in the list - you can see it h ...

Struggles with data retrieval using prisma in a Next.js version 13 implementation

I'm encountering numerous challenges with my Next.js project. I have set up a postgres db and I am utilizing Prisma. There is a file that I created which retrieves data from an API and stores it in the database. Now, I am facing difficulties in using ...