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

Creating Custom Builds with React App by Forking

My React development workflow has evolved with my own webpack setup, but as my projects get bigger, the build process slows down. It's hard for me to optimize it further and having all the development dependencies in the project can be chaotic. I&apos ...

Utilizing React Native Paper and React Native Navigation V5, seamlessly transfer the props from the screen nested under a stack navigator to the shared appbar

My current environment setup looks like this: "react": "17.0.1", "react-native": "0.64.0" "@react-navigation/native": "^5.9.4" "@react-navigation/stack": "^5.14.4" "react- ...

Ways to eliminate a component by selecting a different one in React

Hey everyone, I'm fairly new to React and I've encountered a problem. I'm attempting to create an app similar to Trello. Specifically, I need to be able to remove a component when I click on the close icon of another component. Below is the ...

When the email field is changed, the string is not being set to the state if it is

I encountered a strange issue while setting an email input as a string to state. Even though I can see on React Dev Tools that it gets sent, when I try to log it from another function, I get an empty string. The odd part is, if I change the order of the in ...

What is the best way to position my Jchartfx area graph below my gridview?

When my page loads, the graph appears like this. It consistently shows up in the top left corner even though it should be positioned underneath the grid view as intended. var chart1; function createGraph(mpy) { if (mpy == undefined) mpy = 12.00; ch ...

React flux mouse position resetting upon store emitting a change event

I'm currently working on a page that showcases a collection of articles. When users reach the bottom of the page, they have the option to click on "load more" to fetch additional articles and update the list within the Store. However, I've notice ...

Breaking down an object containing an internal array and omitting specific keys

I've got this specific object structure: const objBefore: { "id": "3pa99f64-5717-4562-b3fc-2c963f66afa1", "number": "5000", "enabled": true, "classes": [ { ...

Encountering issues while trying to deploy a Next JS 13 application on Google Cloud Platform's

Everything was functioning properly with Next version 12, however upon upgrading to Next 13 I encountered the following error. and current node version: "18.x.x" Next Js version: "13.2.1" Step #2: /app/node_modules/next/dist/build/index ...

Tips for positioning bootstrap dropdowns side by side in a row

I'm having trouble aligning my li items in a Bootstrap dropdown next to each other. I've tried everything but nothing seems to work. Here's my code: <nav class="navbar navbar-expand-lg navbar-light bg-light"> < ...

Tips for creating the appearance of a resizable element

My goal was to replicate the resizing and moving functionality of elements in Adobe Illustrator using CSS alone. Unfortunately, I couldn't find any useful resources on how to achieve this. ...

Is it recommended to place JavaScript/CSS at the bottom of an HTML document?

I am currently utilizing jQuery Mobile, and at the moment, my <head> section looks like this: <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1"> <title>help</title> <link ...

Reverting back to the specified CSS style

In my application, I have a common HTML component styled as follows: .box { min-width: 100px; padding: 20px 10px; } There are over 100 of these components and they each have a unique border style without a bottom border: .box:nth-child(1) { border ...

React's CloneElement method now returns an object instead of a function

I'm struggling to wrap my head around the behavior of the React.cloneElement() function. This is what my Component Structure looks like: A.js export default class A extends React.Component { render() { return (<h1>{ this.props.m ...

Different ways to manipulate the CSS display property with JavaScript

Having trouble changing the CSS display property to "none" using JavaScript. Check out my code: <div class="mydiv" onClick="clickDiv1()">hello</div> <div class="mydiv" onClick="clickDiv2()">hi</div> <div class="mydiv" onClick=" ...

Input of data and salt must be provided

(node:35) UnhandledPromiseRejectionWarning: Error: data and salt arguments required. Can someone please assist me in resolving this error that I am encountering? const validatePassword = (password) => { return password.length > 4; }; app.post("/r ...

Changing the date format in DatePicker for Material-UI in a React application

I'm using Material-UI's datepicker, but the default format is "mm/dd/yyyy" and I need to change it to "dd/mm/yyyy", how can this be done? Here is the code for the component: <LocalizationProvider dateAdapter={AdapterDateFns}> <D ...

Maximizing the potential of the autocomplete component in ReactJS: Setting multiple values

Looking for assistance with setting multi selected values for autocomplete in a ReactJS project. The components being used are from Material-UI library. https://i.sstatic.net/Nbu8d.png For example, as shown above, the first data is related to one user an ...

Retrieve the 'computed' CSS for the entire webpage

We operate multiple websites, each referencing 3-5 CSS files. Some of these files are shared across sites while others are specific to certain pages. Our aim is to streamline the CSS structure by consolidating into fewer files without altering the end res ...

Error TS2307: Module './tables.module.css' or its type declarations could not be located

Currently utilizing CSS modules within a create-react-app project and encountering an error within Google Chrome browser: https://i.stack.imgur.com/0ItNM.png However, the error appears to be related to eslint because I am able to close the warning modal i ...

The onClick function for a button is not functioning properly when using the useToggle hook

When the button is clicked, it toggles a value. Depending on this value, the button will display one icon or another. Here is the code snippet: export const useToggle = (initialState = false) => { const [state, setState] = useState(initialState); c ...