"Enhance your forms with RadixUI's beautiful designs for

New to Radix UI and styling components, I encountered difficulties while trying to adapt a JSX component to Radix UI:

Utilizing Radix UI Radio Groups, I aim to style my component similar to this example from Hyper UI with grid layout showing stacked content and checked state: https://i.sstatic.net/FyN7o.png

Key Points

  • Incorporating NextJS 13, TypeScript, and React in my project.
  • Adjusted the code to display radio icon on selection but experienced issues activating borders.
  • The goal is to have block borders with specific styles for selected items.
  • Current implementation includes adding {children} to RadioGroupPrimitive.Indicator which is incorrect as it only handles the button, leading to text appearing only upon selection.

Considering exploring options involving labels, given that selection encompasses entire block along with icon, challenges arise in correctly positioning title and subtitle.

Experimenting further, I arrived at:

//Code snippet here

Followed by frontend call like:

<RadioGroupItemModern key={choice.value} value={choice.value} id={choice.value} defaultValue={field.value || ''}>
    <div>
    <RadioGroupItemTitle>{choice.text}</RadioGroupItemTitle>
    <RadioGroupItemSubtitle>{choice.description}</RadioGroupItemSubtitle>
    </div>
</RadioGroupItemModern>

Currently, desired result displays only when selection is made (albeit invisible).

Exploring Radix Primitives, experimented with various ways of incorporating children, yet struggling to grasp correct logic due to Radix treating group radio and labels as separate components.

Answer №1

If you're looking for the best solution, check out the examples in the shadcn/ui repository here.

In those examples, there are two crucial sets of classes that need to be applied:

  1. The first set should be added to each RadioGroupItem within your RadioGroup. These items should have the classes peer sr-only. The key class here is peer, as mentioned in a different response, which comes from Tailwind.

  2. The second set of classes applies to the element whose visual appearance you want to change when a specific RadioGroupItem is selected. In the example provided, a border is introduced to the Label inside the RadioGroupItem using an attribute selector:

    peer-data-[state=checked]:border-primary
    . This selector looks at the value of the data-state attribute on the button element generated by the RadioGroupItem to determine when to apply the Tailwind class; in this case, it's adding a border-primary, but it could be anything like displaying or hiding an SVG.

These instructions are applicable to RadixUI and shadcn/ui components, utilizing standard attribute selectors for implementation.

If you're curious about the role of peer, you can refer to the relevant documentation on Tailwind's website here!

Answer №2

To make styling adjustments based on sibling state in Radix component, utilize peer from TailwindCSS & aria-checked: instead of checked:. This is necessary because the input is enclosed within a button. Refer to this simple implementation using RadixUI & shadcn/ui:

<FormItem className="block w-full space-x-3 space-y-0">
  <FormControl>
    <RadioGroupItem value="myValue" className="peer hidden" />
  </FormControl>
  <FormLabel className="block cursor-pointer rounded-md border border-border p-4 font-normal shadow-sm hover:border-primary peer-aria-checked:border-primary peer-aria-checked:ring-1 peer-aria-checked:ring-ring">
    My Label
  </FormLabel>
</FormItem>

Answer №3

Recently, I came across a solution that I forgot to share earlier. In the library creator shadcn's Examples, there is an interesting use of the &:has([data-state=checked] attribute from Radix UI. This attribute is utilized to handle the checked item.

The creator uses this attribute as a boolean to apply the border-primary class:

<FormLabel className="[&:has([data-state=checked])>div]:border-primary">

To explore further details, check out the GitHub Repo here.

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

Customizing page layout for pages wrapped with higher-order components in TypeScript

Looking to add a layout to my page similar to the one in this link: layouts#per-page-layouts The difference is that my page is wrapped with a HOC, so I tried applying getLayout to the higher order component itself like this: PageWithAuth.getLayout Howev ...

What is the best method for expanding nodes after the tree has been loaded?

Greetings! I am currently working on a web application using Angular 5. One of the features I have implemented is loading trees onto my webpage. These trees are populated with data from an API and are designed to be dynamic. After loading the tree, my goal ...

Leveraging the useEffect hook to facilitate login functionality through local storage

I am currently working on a React and Next.js application that requires authorization. I am facing an issue with retrieving the token from local storage. If I try to do this without using useEffect, I encounter an error stating undefined localstorage. Ho ...

Refresh PrimeNG dataTable without reloading the table

Currently, I am implementing the functionality of adding new rows to a dataTable in my template. Here is the code snippet from the component: rows: any = {} newrow: any = {} addNewRow(key: string) { let rows = {...this.rows} let newrow = {_key: Math ...

Declarations of Typescript React for Props for Specific Element

I am trying to specify types for certain elements like <button> or <input>, but I am unable to differentiate between specific element types. Here is an example: interface Props{ component: React.ComponentProps<"button"> | nev ...

Is it possible to call a function directly from useEffect?

Code VersionA: useEffect(() => doRequest(), []); Code VersionB: useEffect(() => { doRequest(); }, []); I used to believe that both versions were the same, with VersionA being a shortcut and VersionB allowing for multiple commands within the inlin ...

The user model cannot be assigned to the parameter of type Document or null in a mongoose with Typescript environment

While working with Typescript, I encountered an error related to mongoose. The issue arises from the fact that mongoose expects a promise of a mongoose document (in this case, the user's document) or "null" to be resolved during a search operation. Ho ...

Tips for sending information back to the previous screen in React Native Navigation version 5

Recently, I upgraded to react native navigation version 5 and now I am facing an issue with sending data back to the previous screen when making a goBack() call. To navigate to the next view, I use: const onSelectCountry = item => { console.log(it ...

Accessing Properties or Methods in Angular2 Components

My application consists of 3 main components: PageMenu, LoginSession, and LoginForm. The purpose is to establish a connection between the variables in LoginSession and PageMenu, allowing for the proper functionality of the LoginForm component. PageMenu: ...

A method for modifying the key within a nested array object and then outputting the updated array object

Suppose I have an array called arr1 and an object named arr2 containing a nested array called config. If the key in the object from arr1 matches with an id within the nested config and further within the questions array, then replace that key (in the arr1 ...

Utilizing interface in NestJS for validating incoming request parameters

My goal is to utilize the interface provided by class-validator in order to validate a specific field in the incoming request body. Here's the interface structure: export enum Fields { Full_Stack_Dev = 'full stack dev', Frontend_Dev = &a ...

Issue with the reload animation jumping too quickly in Framer Motion on NextJS

While creating an animation for my landing page using NextJS with framer motion, I encountered a strange behavior after deploying the site. The animations started to happen too quickly and it felt a bit off. During development on localhost using Chrome, ev ...

Creating an interactive element in Angular: A step-by-step guide

Hey there, I'm facing a problem with creating a specific payload structure as shown in the example code snippet below. Everything was going well until I got stuck at the dynamic form part, and despite several attempts, I can't seem to figure it o ...

The next/router is throwing an error because it cannot access the property 'pathname' when running in storybook mode

Currently, I have developed an app utilizing Next.js and MaterialUI. To ensure the Link component works seamlessly with MaterialUI, I have implemented a customized Link component outlined below: function Link(props) { const { href, activeClassNa ...

Exploring Next.js with getServerSideProps

My code has a warning from the console attached. I would appreciate it if someone could help me identify the problem... When I use the "data" hardcoded as props, I can display them in the components, but when I try to fetch from an API, I can retrieve the ...

The error message "Multiple children error occurs when an empty link in Next.js

Is there a way to successfully implement a <Link /> element without any content inside it in my application? Surprisingly, when I don't provide any content, I encounter the multiple children error, even though the opposite seems to be happening. ...

How do React Native proxies differ from vanilla React proxies in their functionality?

Trying to retrieve data from an API running locally on port 5000 of my device, I recalled setting the proxy in package.json when working on React web applications: "proxy": "https://localhost:5000" Attempting to fetch information f ...

Remove an item from the DOM instantly with React

Having trouble synchronously removing a child from the container? Here is a simplified code snippet demonstrating the current solution using the useState hook. type ChildProps = { index: number; id: string; remove: (index: number) => void; }; fun ...

How can you reposition a component within the dom using Angular?

Just started learning Angular, so I'm hoping this question is simple :) Without getting too specific with code, I could use some guidance to point me in the right direction. I'm currently developing a small shopping list application. The idea i ...

tips for successfully indexing dynamic routes on Google with NextJS

Although I am familiar with ReactJS, I am currently working on developing a web page using NextJS to enhance SEO. However, I have encountered a question. How can I ensure that Google recognizes the dynamic routes created with NextJS? I know about getStati ...