Home > Software design >  Add text in border of a chip Material UI
Add text in border of a chip Material UI

Time:05-05

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.

CodePudding user response:

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"
  }
}));
  • Related