Incorporate props within the CSS template string of Emotion for enhanced styling flexibility

I am currently in the process of transitioning my design system from styled-components to emotion.

Within styled-components, the following syntax is considered valid:

export interface AvatarProps {
  // ...
  shape: AvatarShape;
  size: AvatarSize;
}

const borderRadiusByShape = css<Pick<AvatarProps, "shape" | "size">>`
  border-radius: ${(props) => {
    return match(props.shape)
      .with("circle", () => `${props.size}px`)
      .with("square", () => "0px")
      ...
      .exhaustive();
  }}
`;

const StyledAvatar = styled.div<AvatarProps>`
  /* ... */
  ${borderRadiusByShape};
`;

This approach allows for the reuse of borderRadius in various styled.[x] declarations.

Upon reviewing emotion's css function, it appears that emotion does not support this syntax. Is there a workaround that would eliminate the need to encapsulate this functionality within a new component?

Answer №1

After some investigation, I discovered that I can extract the properties from the css and create a function to process these properties and generate the corresponding CSS:

export interface AvatarProps {
  // ...
  shape: AvatarShape;
  size: AvatarSize;
}

const calculateBorderRadius = (props: Pick<AvatarProps, "shape" | "size">) => css`
  border-radius: ${match(props.shape)
    .with("circle", () => `${props.size}px`)
    .with("square", () => "0px")
    /* ... */
    .exhaustive()};
`;

const StyledAvatar = styled.div<AvatarProps>`
  /* ... */
  ${calculateBorderRadius};
`;

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

Aligning an SVG within a container div

I am trying to display an SVG image inside a fixed-position div. Here is the HTML: <div class="main"> <svg class="svg" viewBox="0 0 180 100"> <rect height="100%" width="100%" fill="#003300"></rect> </svg> </div> ...

Assistance needed with dynamically resizing a background image

Is there a way to automatically adjust the size of a background image for an element? For instance, I want my links in HTML to have a background image with slanted borders and rounded corners. Usually, you would set the width of the anchor element to fit t ...

Is there a way to detect when the mobile keyboard is open in a React application?

I am currently working with a Textfield that includes the Autofocus attribute. I am wondering if there is a method to detect when the keyboard opens in mobile view and then store this information in a boolean variable. https://i.stack.imgur.com/z0EtB.png ...

React component properties fail to update

Hey there! I am currently working on developing a React Component that consists of a simple label which changes its content whenever a SignalR method is triggered. Below is an example of my React component: var PersonalityStatusApp = React.createClass({ ...

Retrieving information from a TableRow element within Material UI

In the latest version of Material UI, I am utilizing a Table component but struggling to figure out how to fetch data from a selected row. The Table component's documentation mentions an onRowSelection prop that provides only the RowNumber of the sel ...

How to Disable Autofill Background Color in React Material UI

I have been struggling to find a solution for removing the background color of autofill selection. Whenever I use an autofill value, the background color changes to a different color. View Current Issue I have tried using the workaround: -webkit-box-sha ...

The Angular Material table does not adapt to different screen sizes

I developed an Angular application using Angular Material that features a table with 22 columns. However, when I expand the browser window, some columns are hidden. Additionally, on mobile browsers, not all columns are displayed. I have attempted the follo ...

Use JavaScript to load and set a background image for a div

When it comes to loading different images onto an "img" tag by printing their URLs using JavaScript and then letting CSS manipulate the content in the tag, I have a code snippet that does just that. $(window).load(function() { var randomImages = [&apo ...

Using jQuery to toggle sliding the information above a div

I am facing an issue with my customized sliding menu. The menu slides over the image but not over the content-div, pushing it aside. I have tried to fix this problem but haven't found a solution yet. My goal is for the menu to slide over all divs and ...

The element fails to appear on screen when using Firefox

Check out this site using IE or Chrome and pay attention to the yellow block: Then, try opening the same page in Firefox and watch as the block mysteriously vanishes. Does anyone have any idea why this is happening? Did I make a mistake somewhere? ...

Utilize a combination of filters within a Redux action

Is it possible to implement multiple filters in a Redux action? I am looking to filter based on four fields: name, entity, status, and value. case SEARCH_ALERTS: return { ...state, alertList: state.alertList.filter(item => item. ...

Conceal a Column in Material UI Data Grid Filter

I've managed to conceal the id within the columns, but how can I also hide it in the filter? <StyledDataGrid getRowId={(r) => r.newId} columns={columns} rows={rows} disableSelectionOnClick checkboxSelection />; const columns = [ ...

The integration of ag-grid webpack css is not reflecting on the website as intended

I'm facing an issue with ag-grid in my react application where I can't seem to get the CSS working properly with webpack. The grid is currently displaying like this: image: https://i.sstatic.net/RPKvH.png const path = require("path"); var webp ...

Navigating through pages in a server component using Next.js

I am currently working on a project that involves implementing pagination using the NextJS 13 server component without relying on the use client. The goal is to ensure that when a button is clicked, new entries are added to the screen in a sequential order ...

What is the best way to replicate a div's background color using an image within the body element?

I am looking to achieve a layout similar to the one below: https://i.sstatic.net/1cOYw.png The dark grey color represents the sidebar, but I want to use this color as a repeating vertical image in the body element without covering the footer (light gray) ...

The Express server is failing to establish a connection with Node.js due to an error in the

import React, { useState, useRef, useEffect } from 'react' import user from '../components/Client'; import Editor from '../components/Editor'; import { initSocket } from '../socket'; import ACTIONS from '../acti ...

Space between an image and a div element

While creating a website in Dreamweaver CC, I noticed a significant gap between my image and a div tag. Here is a screenshot for reference: Below is the code from my index file: <!doctype html> <html> ... </div> Additionally, here is a ...

Achieving automatic div width using CSS

I am dealing with an HTML structure that can vary depending on the page context. In some instances, it appears like this: <div class="container"> <div class="column"> blah </div> </div> While on other pages, it looks l ...

Guide user to different screen in React Navigation depending on context state

In my project, I have introduced a new state called roleSelected. Initially, the value of this state is set to false, and it is managed within my AuthContext. const [roleSelected, setRoleSelected] = useState(false); The configuration of my stack navigatio ...

Restrict HTML Elements Based on Their Size

I have a text file with a substantial amount of content that I need to display in an HTML format. The challenge is that I only want to show a portion of the text on the screen, but I am unsure of the exact amount that needs to be displayed. What I do know ...