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

The hyperlink function is not operational in Gmail attachments

Using an anchor tag to navigate to a specific section within the same page works perfectly when the HTML file is on my local machine. However, when I attach the file in Gmail and open the attachment, it doesn't work. Why is this happening? How can I m ...

Issue in MUI V5: MakeStyles styles being overridden

After recently updating to version 5.0.0-alpha.25 (moving from 5.0.0-alpha.10), I've encountered an issue with makeStyles not working properly. Despite checking for any breaking changes, I couldn't find anything related to this specific problem, ...

How can I convert a PHP class into inline CSS styles?

While exploring MailChimp's css inliner at , I found myself curious if there are any available classes that can achieve the same result. It would be convenient to have this functionality directly in my email code without relying on MailChimp. I am es ...

Wildcard routes for publicly accessible files

I have a collection of "widgets" with both client and server-side .coffee files (client representing Backbone.js model/view and server corresponding to ExpressJS routes), all organized within the main project directory: my-node-expressjs3-project/ src/ ...

How can I transfer an instance of a class to dataTransfer.setData?

So I created a new instance of a class: let item = new Item(); Next, I attempted to serialize the item and add it to dataTransfer for drag and drop functionality: ev.dataTransfer.setData("info", JSON.stringify(item)); At some point, I need to retriev ...

Tips on managing a component's storage and rendering based on conditions

While using the material-ui popover component to encapsulate a formik form, I've noticed that every time it closes, the form re-renders and all values are cleared. I considered storing values in the parent component, but due to the complexity and use ...

Transforming intricate JSON data into a structured table format

I'm struggling to transform the nested JSON data into an HTML table, but I keep encountering an error. I'm uncertain about where I may have made a mistake. Could it be related to how I am trying to access the array within the object? Here' ...

Display a custom toast from a list using Bootstrap 5

I've been utilizing the toast feature from Bootstrap, and it works perfectly when displaying a single toast. However, I encountered an issue when trying to display a specific toast, like an error toast, from a list of predefined toasts. It ended up sh ...

Optimal data structure for storage in a Next.js project with TypeScript

What is the appropriate data type for store in export let store: any; other than any? I have used @ts-igore to suppress TypeScript errors on the last line. How can I address the TypeScript error for that as well? I mentioned the boilerplates utilized in ...

Tips on obtaining the screen resolution and storing it in a PHP variable

Hey there! I've run into a bit of a roadblock that I'm struggling to overcome. I know that I need to incorporate some JavaScript to solve this issue, but I'm having trouble grasping how to do so. Here's the script I'm working with: ...

Steps to include a personalized function in a Mongoose Model

One way to extend Mongoose is by adding methods to documents. Here's an example: const userSchema = new mongoose.Schema({ balance: Number }) userSchema.methods.withdrawBalance = function(amount){ const doc = this doc.balance = doc.balance - amou ...

Determining if a div is scrolled to the bottom in ASP.NET

Seeking help as I am unsure how to tackle this task. My project involves using asp.net, where I have a div that has overflow:auto enabled to display terms and agreements. Additionally, there is an asp.net checkbox control with visibility set to "false". ...

Changing the counter using dual buttons in Vue.js

I am facing an issue with updating the counter when using both the add and remove buttons. The add button functions correctly, but unfortunately, the delete button does not update the counter as expected. Below is a picture showcasing the problem at hand: ...

Attempting to utilize the LLL algorithm as described on Wikipedia has led to encountering significant challenges

I'm struggling with determining whether my issue stems from programming or understanding the LLL algorithm mentioned on Wikipedia. To gain a better understanding of the LLL algorithm, I attempted to implement it following the instructions outlined on ...

Modify the length of an array using a number input field

Currently, I am working with an array that contains objects and I want to dynamically change the number of objects in this array based on user input from a number type input box. Whenever the number in the input box is increased, I need to increase the len ...

JavaScript Time Counter: Keeping Track of Time Dynamically

Currently, I am attempting to create a dynamic time counter/timer using JavaScript. Why dynamic? Well, my goal is to have the ability to display days/hours/minutes/seconds depending on the size of the timestamp provided. If the timestamp is less than a d ...

Angular alert: The configuration object used to initialize Webpack does not conform to the API schema

Recently encountered an error with angular 7 that started popping up today. Unsure of what's causing it. Attempted to update, remove, and reinstall all packages but still unable to resolve the issue. Error: Invalid configuration object. Webpack ini ...

Replace async/await with Promise

I want to convert the async/await code snippet below: const mongoose = require('mongoose') const supertest = require('supertest') const app = require('../app') const api = supertest(app) test("total number of blogs" ...

Asynchronously updating a Django model instance in real-time

On my website, there is a button that allows users to view notifications as a drop-down without navigating away from the current page. I am interested in updating the unread field of every notification for a user from True to False when this button is clic ...

What is the trick to having the ball change colors every time it hits the wall?

Recently, I stumbled upon this interesting ball bouncing question while searching for some JavaScript code. While the basic bounce animation was simple to achieve, I started thinking about how we could make it more dynamic by changing the color of the ball ...