One helpful tip for adjusting the size of a UI chip on the fly

I am attempting to adjust the size of a UI chip dynamically based on the font size of its parent elements using the em unit in CSS.

My objective is to achieve something like this:

style={{size:'1em'}}

The issue I'm encountering: The chip element in material-ui does not seem to be easily resizable compared to other components in material-UI.

Attempts made:

  1. style={{transform:'scale(1em)'}} was tried but it did not yield the desired outcome. The anchor point for the transform operation was difficult to manage.
  2. Another approach involved creating a custom chip with
    <img style={{float: 'left', width: '1em', borderRadius: '50%',}}/>
    . However, this solution lacked the original appearance of the material UI chip.
import Avatar from '@material-ui/core/Avatar'
import Chip from '@material-ui/core/Chip'

function Chips() {
  const classes = useStyles()

  const handleDelete = () => {
    console.info('You clicked the delete icon.')
  }

  const handleClick = () => {
    console.info('You clicked the Chip.')
  }

  return (
    <div className={classes.root}>
      <h1>
        <Chip
          //style={{size:'1em'}}
          avatar={<Avatar alt="Natacha" src="/static/images/avatar/1.jpg" />}
          label="Deletable"
          onDelete={handleDelete}
        />
      </h1>

      <h4>
        <Chip
          //style={{size:'1em'}}
          avatar={<Avatar alt="Natacha" src="/static/images/avatar/1.jpg" />}
          label="Deletable"
          onDelete={handleDelete}
        />
      </h4>
    </div>
  )
}

Answer №1

At the moment, the Chip component does not have built-in support for adjusting size (We hope this feature will be added in the future 🤞).
To work around this, you can create your own custom component. I've developed one called CustomChip.

Within this custom component, include a prop called size to adjust the chip's dimensions accordingly.

CustomChip.js

function CustomChip(props) {
  const { size = 1, ...restProps } = props;
  const classes = useStyles({ size });

  return (
    <Chip
      className={classes.root}
      classes={{ avatar: classes.avatar, deleteIcon: classes.deleteIcon }}
      {...restProps}
    />
  );
}

const useStyles = makeStyles((theme) => ({
  root: {
    fontSize: (props) => `${props.size * 0.8125}rem`,
    height: (props) => `${props.size * 32}px`,
    borderRadius: "9999px"
  },
  avatar: {
    "&&": {
      height: (props) => `${props.size * 24}px`,
      width: (props) => `${props.size * 24}px`,
      fontSize: (props) => `${props.size * 0.75}rem`
    }
  },
  deleteIcon: {
    height: (props) => `${props.size * 22}px`,
    width: (props) => `${props.size * 22}px`,
    color: "green"
  }
}));

This custom component adjusts its size based on the provided input.

Example of how to use it:-

<CustomChip
    size={2}
    avatar={<Avatar alt="Natacha" src="/static/images/avatar/1.jpg" />}
    label="Deletable"
    onDelete={handleDelete}
/>

Check out the working demo on Codesandbox:

https://codesandbox.io/s/crazy-blackwell-987it?fontsize=14&hidenavigation=1&theme=dark

Answer №2

As a result of the deprecation of makeStyles() in version 5, it is advisable to opt for a more up-to-date styling solution like sx or styled.

Here is an illustration using a custom component and sx:

import React from 'react';

import { ChipProps } from '@mui/material/Chip/Chip';
import { Chip } from '@mui/material';

type ChipAtomProps = ChipProps & {
  scale?: number;
};

const ChipAtom: React.FC<ChipAtomProps> = ({
  id,
  className,
  variant,
  scale = 1,
  avatar,
  label,
}) => {
  const scaledChipSx = {
    height: `${scale * 32}px`,
    borderRadius: `${scale * 16}px`,
    '& .MuiChip-label': {
      paddingRight: `${scale * 12}px`,
      paddingLeft: `${scale * 12}px`,
      fontSize: `${scale * 0.8125}rem`,
    },
    '& .MuiChip-avatar': {
      width: `${scale * 24}px`,
      height: `${scale * 24}px`,
      fontSize: `${scale * 0.75}rem`,
    },
  };

  return (
    <Chip
      id={id}
      className={className}
      variant={variant}
      avatar={avatar}
      label={label}
      sx={scaledChipSx}
    />
  );
};

export default ChipAtom;

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

Develop a cutting-edge application using React, Node, and deploy it seamlessly

I'm fairly new to this and I've created a React frontend and Node backend application that I'm trying to deploy in Docker. However, I'm encountering an error mentioning Python and issues with Couchbase installation. Can someone please a ...

Displaying text on an image when hovering over it

I have tried various solutions that I came across, but none of them have been successful so far. My goal is to display dynamic text over an image when the user hovers over it. Additionally, I would like to change the hover color. Currently, the text is alw ...

Attempting to align three sections horizontally

I'm having trouble with my current HTML code and I can't seem to figure out what the issue is. As a beginner in HTML, I am struggling to understand. My goal is to have three columns: one on the left taking up 20% of the space, one in the center t ...

What is the process for setting up a webpack alias for React and React-DOM in Next.js?

Recently, I made some changes to my next.config.js file where I created an alias for react and react-dom. Below is a snippet of my next.config.js: var path = require("path"); module.exports = (phase) => { return { webpack5: true, webpack(conf ...

Assistance with Parallax Mouse Movement, Using JQuery, HTML, and CSS

As a newcomer to JQuery, I decided to experiment with creating a parallax background effect using the mousemove function. By utilizing event.pageX to generate a variable for adjusting the background position, I was able to achieve the desired result. Alth ...

"Converting a text into a property that can be

In my scenario, I have a set of fixed options along with a dynamic number of yes/no radio inputs named other[index]. By utilizing $(form).serializeArray(), I can obtain an array of name/value objects. Through the use of the reduce method, I am then able to ...

Utilize JavaScript declarations on dynamically added strings during Ajax loading

Is there a way to append HTML strings to the page while ensuring that JavaScript functions and definitions are applied correctly? I have encountered a confusing issue where I have multiple HTML elements that need to be interpreted by JavaScript. Take, for ...

What is the best way to achieve the functionality of this ajax jquery using vanilla JavaScript?

I am attempting to replicate this jQuery ajax POST request in Vanilla JS, which currently looks like: $.ajax({ method: 'POST', url: window.location.href + 'email', data: { toEmail: to, fromName: from, ...

Steps to deactivate two choices in a multi-select dropdown menu and visually dim those options

Hey there, I recently worked with Angular8 and Bootstrap 4. I utilized a Bootstrap multi-select dropdown, where I encountered an issue: specifically, I'm trying to disable and gray out the options for PL Marketing and CL Marketing but have been unsucc ...

What is the method to ensure background images are loaded with SSL from a different domain?

I run an online store and to improve performance, the images are hosted on a different domain. However, when I switch to secure mode using SSL on certain parts of the website, the background images disappear. Trying to view the image directly in the browse ...

Transmit JavaScript code from ASP.NET

Trying to transfer JavaScript code built using String Builder on the server-side (ASP.NET) to the HTML page's JavaScript. Here is my approach: Utilizing a Master Page and an ASPX page structured like this: <asp:Content ID="BodyContent" ContentPla ...

Key press event not firing as expected

<multiselect v-model="value" :options="websites" label="url" track-by="url" :allow-empty="false" class="header-select mr-3" v-on:keyup.enter="submit"></multiselect> My requi ...

I am seeing an empty dynamic HTML table

I have been working on creating a dynamic HTML table, but I am facing an issue where the data is not displaying in the table. I have verified that the query is correct by testing it in SQL and confirming that it outputs the data. The problem seems to lie w ...

Avoid the problem of animations triggering twice when clicking

Hey there, I am facing an issue with my slider. If you could take a look at this website , you will notice that after clicking on the arrows, the slider behaves asynchronously. It changes speed rapidly at times and then slows down, repeating this pattern ...

Error: cannot use .json data with `filter` method from WEBPACK_IMPORTED_MODULE_2__["filter"]

There seems to be an error occurring when attempting to retrieve data from a JSON file in the specific line of code selectedEmployee: employeeList.data.Table[0], An issue is arising with TypeError: _employeeList_json__WEBPACK_IMPORTED_MODULE_2__.filter ...

The map fails to load on the HTML page

I am struggling to load a map into my HTML page from a file located in the app folder. Despite using the correct code for inserting the map, it still does not load properly. <!-- Contact section start --> <div id="contact" class="contact"> ...

Tips for integrating a back button functionality with AJAX requests

My single page web application allows users to enter genre, date range, and other inputs before making an ajax post request to a Java Spring MVC server. Despite everything working well, I now want to implement a back functionality. If a user wants to go b ...

Incorporate multiple array values within an if statement

Looking to dynamically change the background image of an element based on specific strings in the URL. Rather than changing it for each individual term like "Site1", I want to be able to target multiple words. Here's what I've tried: var urlstri ...

The most efficient method for documenting $.trigger in JavaScript/jQuery is through the use of JSD

When it comes to documenting in jsDuck, what is the optimal method for capturing the following event trigger: $(document).trigger('myCustomEvent'); ...

Is it recommended to have react and react-dom listed as devDependencies in the package.json file?

As I utilize webpack to package all files for web production, and no code is executed on node during this phase, rendering no packages required in production, should all dependencies be designated as development only? A response based solely on logic, rat ...