Add text in border of a chip Material UI

Issue

enter image description here

I need to create this style with a Chip component pre build with MaterialUI

with html and css the solution will be using Some Text

but even there the result will not be the same, I saw some example achieving the same with material but using a TextField with an adornment of the Chip but it’s not the same.

Solution

If you really want to use the <Chip> component, you could use &::before on the Chip styling.

Eg:

const Chip = styled(MuiChip)(({ chipTitle }) => ({
  "&::before": {
    content: `"${chipTitle}"`,
    position: "absolute",
    top: "-8px",
    left: "16px",
    backgroundColor: "#fff",
    padding: "0 8px"
  }
}));

And use it as:

<Chip
  label="Salary Proposal - 500k$"
  variant="outlined"
  onDelete={handleDelete}
  chipTitle="Hello"
/>

Check out this CodeSandbox. Of course, there might be some difference in terms of personal styling, but update it as necessary.

If you are using Typescript:
You need to first create the type that extends the default ChipProps.
eg:

import {styled, Chip as MuiChip, ChipProps as MuiChipProps} from '@mui/material'

interface ChipProps extends MuiChipProps {
    chipTitle: string
}

Afterwards, modify the styled() as follows:

const Chip = styled(MuiChip)<ChipProps>(({ chipTitle }) => ({
  "&::before": {
    content: `"${chipTitle}"`,
    position: "absolute",
    top: "-8px",
    left: "16px",
    backgroundColor: "#fff",
    padding: "0 8px"
  }
}));

Answered By – marius florescu

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.