Creating sibling classes with tailwind using the map function

Currently, I am combining tailwind, react, and nextjs to develop a website. My goal is to implement the check radio button technique to dynamically display different content on the website without relying on JavaScript. To streamline data management, I am considering using an array of objects like [{name: string, content: string}, ...]. The specific section of tailwind documentation that guided me through this process can be found here: differentiating peers

I am thinking about replacing the

class="peer/draft"

with

className={`peer/${item.name}`}`

since it is enclosed within the array.map((item) => { ... }) loop.

The following code snippet successfully accomplishes the task because:

If I directly use the compiled pure HTML code generated by nextjs in the client-side browser, the sibling elements interact seamlessly.

However, if I allow nextjs to compile and deliver the HTML code to the client browser, it fails to respond when a radio button is clicked!

Below is an example of my code including relevant data:

export default function page() {
    const jobs = [
        {
            name: "walker",
            id: "wlk",
            conditions: "20 an hour",
            content: "walk and walk"
        },
        {
            name: "sitter",
            id: "sit",
            conditions: "20 an hour",
            content: "sit and sit"
        },
    ]

    return (
        <section id="careerHome">
            <div className="container grid md:grid-cols-2">
                {jobs.map((item) => {
                    return (
                        <div
                            key={item.id}
                            className="shadow-lg p-10 text-center capitalize flex-1 mt-6 rounded-md flex flex-col relative"
                        >
                            <h3>
                                {item.name}
                            </h3>
                            <input id={item.id} className={`peer/${item.id}`} type="radio" name={item.id} />
                            <b className="text-start">Learn More</b>
                            <div className="h-4"></div>
                            <input id={`${item.id}Close`} className={`peer/${item.id}Close`} type="radio" name={item.id} />
                            <b className="text-start">Close</b>
                            <div className={`hidden peer-checked/${item.id}:block absolute top-20 right-[10%]`}>
                                <p>{item.conditions}</p>
                            </div>
                            <div className={`hidden peer-checked/${item.id}:block`}>
                                <p>{item.content}</p>
                            </div>
                        </div>
                    )
                })}
            </div>
        </section>
    )
}

Each block should consist of two buttons - one for opening and one for closing the block.

Is there a way to utilize generative functions to assign tailwind classes?

If you have suggestions on better practices or recommendations, please feel free to share your insights!

Answer №1

According to the guidelines:

An important factor in how Tailwind recognizes class names is that it only identifies classes that appear as complete and unbroken strings in your source files.

If you use string interpolation or combine partial class names together, Tailwind will not detect them and therefore will not create the corresponding CSS:

Avoid constructing dynamic class names

<div class="text-{{ error ? 'red' : 'green' }}-600"></div>

In the given example, the strings text-red-600 and text-green-600 are not recognized, so Tailwind will not generate those classes. Instead, ensure that all class names used are complete:

Always include full class names

<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>

Considering that the peer element and its related entities are enclosed within individual parent <div> elements, and only one peer is being utilized (as peer/${item.id}Close remains unused), there is no necessity for labeled peers:

function Page() {
  const jobs = [
    {
      name: 'walker',
      id: 'wlk',
      conditions: '20 an hour',
      content: 'walk and walk',
    },
    {
      name: 'sitter',
      id: 'sit',
      conditions: '20 an hour',
      content: 'sit and sit',
    },
  ];

  return (
    <section id="careerHome">
      <div className="container grid md:grid-cols-2">
        {jobs.map((item) => {
          return (
            <div
              key={item.id}
              className="shadow-lg p-10 text-center capitalize flex-1 mt-6 rounded-md flex flex-col relative"
            >
              <h3>{item.name}</h3>
              <input
                id={item.id}
                className="peer"
                type="radio"
                name={item.id}
              />
              <b className="text-start">Learn More</b>
              <div className="h-4"></div>
              <input id={`${item.id}Close`} type="radio" name={item.id} />
              <b className="text-start">Close</b>
              <div className="hidden peer-checked:block absolute top-20 right-[10%]">
                <p>{item.conditions}</p>
              </div>
              <div className="hidden peer-checked:block">
                <p>{item.content}</p>
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<Page/>);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js" integrity="sha512-QVs8Lo43F9lSuBykadDb0oSXDL/BbZ588urWVCRwSIoewQv/Ewg1f84mK3U790bZ0FfhFa1YSQUmIhG+pIRKeg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js" integrity="sha512-6a1107rTlA4gYpgHAqbwLAtxmWipBdJFcq8y5S/aTge3Bp+VAklABm2LO+Kg51vOWR9JMZq1Ovjl5tpluNpTeQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.tailwindcss.com/3.4.3"></script>

<div id="app"></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

Exploring the usage of the Date method in React

When I insert the given code snippet import React,{Component} from 'react'; import ReactDOM from 'react-dom'; import './index.css'; class Date extends React.Component{ dataToString = (d) =>{ ...

Material-UI: Creating Radio Button Groups

I have been working on a project using React and Bootstrap. I decided to switch to material-ui, which went smoothly except for the radio buttons. Below is the original code that worked well: <label> <input type={that.props.questionType} name ...

Having trouble with the Three.js OBJ loader in CodePen?

Currently, I am experiencing a challenge with loading an OBJ file on Three.js. Oddly enough, the functionality seems to be working perfectly fine when I deploy the files on my server as demonstrated here: However, when attempting to run it on Codepen, I e ...

Using React for partial server-side rendering (SSR) of a webpage

Scenario: Our current setup involves using SSR with react for anonymous users and everything is running smoothly. Now, we are considering implementing SSR for authenticated users as well, but we lack the necessary testing to ensure that our system can han ...

The element is implicitly assigned an 'any' type as the expression of type 'any' cannot be used to index a type with createStyles

My stylesheet looks like this: const badgeStyle = createStyles({ badge: { borderRadius: "12px", padding: "5px 12px", textTransform: "uppercase", fontSize: "10px", fontWeight: 700, lineHeight ...

Is there a way to give only the left corners of a button a rounded look?

Here is the visual representation of the button: https://i.stack.imgur.com/Bjlkp.png ...

Make sure to only update the state in useEffect after retrieving the data from the localStorage

Trying to troubleshoot the continuous looping and crashing issue in my app caused by passing variables in the dependency array of the useEffect hook. These variables are state variables from the context provider. The goal is to make the useEffect hook run ...

The NextJS Middleware.ts file failed to activate

Currently, I am working on a NextJS React Project with a unique file structure setup. In my project, src/app contains all pages without a specific src/app/pages folder. For example, the login page is accessed through "/login" where src/app/login/ ...

Tips for integrating Material UI with useRef

There seems to be an issue with the code, but I haven't been able to pinpoint exactly what it is. My question is: How do you properly use useRef with Material UI? I am attempting to create a login page. The code was functioning fine with the original ...

Utilizing Material-UI List components within a Card component triggers all onClick events when the main expand function is activated

Need help with Material-UI, Meteor, and React I am trying to nest a drop down list with onTouchTap (or onClick) functions inside of a card component. While everything renders fine initially, I face an issue where all the onTouchTap events in the list tri ...

The navigation bar on the website highlights vibrant green arrows next to the

I'm having trouble implementing a bootstrap menu on my website using the code provided by Bootstrap. The menu is not displaying correctly and instead showing small green UL arrows. I have JavaScript and Bootstrap scripts in my project. Is there a way ...

What causes Secure Local Storage to occasionally return null?

Hey there! I'm currently working with Firebase Google Auth and securely storing data in local storage. To ensure that the user exists on every route, I retrieve the user from local storage. The application is running smoothly, but occasionally my secu ...

What is the latest CSS browser support for the min() and max() functions in 2018?

I am considering implementing the use of the min() and max() functions in my project. I'm curious about the current browser support as of 2018. Do you think it is necessary to include the @supports at-rule? For example, I could write: .px-4-safe { ...

The function signature '() => void' cannot be assigned to a variable of type 'string'

Encountering an issue in Typescript where I am attempting to comprehend the declaration of src={close} inside ItemProps{}. The error message received reads: Type '() => void' is not assignable to type 'string'. Regrettably, I am un ...

Efficient Ways to Reduce Textfield Re-renders

One issue that has caught my attention is the fact that every component within the same parent element (App in the example below) seems to rerender when unrelated states/props change, causing noticeable slowdown in the page/forms. Despite following variou ...

Setting the minimum and maximum width of a div using Bootstrap, not based on the number of columns

I want to adjust the number of columns based on the width of the screen rather than choosing a specific value like 3, 4, 5, or 6. ...

Extracting specific key-value pairs from JSON data

Working with JSON data, I encountered a need to pass only specific key-value pairs as data to a component. Initially, I resorted to using the delete method to remove unwanted key-value pairs, which did the job but left me feeling unsatisfied. What I truly ...

Troubleshooting Error in Converting a JSX File with Tailwind CSS and Typescript

I found a code example on the Tailwind website. However, when I changed the file extension to .tsx, I encountered an error related to the className attribute. Do I need to specify a type for the className variable? What steps should I take to resolve thi ...

tips for fixing npm bug in next js application

I am a project built on Next.js/React.js. During local development, everything functions perfectly and all updates reflect on the site as expected. I have deployed this project using Azure, with my repository hosted on Github Actions. Furthermore, I have s ...

How can you substitute sections of a sentence with an array of strings?

I have a specific sentence that needs formatting: span class="searchmatch" Program /span, programme, programmer, or span class="searchmatch" programming /span may refer to: span class="searchmatch" Program /span management, th ...