1

how to make asterisk red & bold in Textfield in material UI. I have a placeholder text without label.my label is null or empty. I want to make placeholder star RED. is it possible ?? here is my code https://codesandbox.io/s/elegant-morse-ksck6t?file=/demo.tsx:329-451

any idea

 export default function BasicTextFields() {
  return (
    <Box
      component="form"
      sx={{
        "& > :not(style)": { m: 1, width: "25ch" }
      }}
      noValidate
      autoComplete="off"
    >
      <TextField
        id="outlined-basic"
        label=""
        placeholder="ddd *"
        variant="outlined"
      />
    </Box>
  );
}
user5711656
  • 3,310
  • 4
  • 33
  • 70

1 Answers1

0

It would be easily achievable with the ::after pseudoelement, but unfortunately, we cannot use it in React's inline CSS styles. Instead, we have to create a separate element, adjust its position and visibility manually, like so:

import * as React from "react";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";

export default function BasicTextFields() {
  //Hide the asterisk when the input field has a value
  const [hideAsterisk, setHideAsterisk] = React.useState(false);
  const onInputChange = React.useCallback((event) => {
    setHideAsterisk(Boolean(event.target.value));
  }, []);

  return (
    <Box
      component="form"
      sx={{
        "& > :not(style)": { m: 1, width: "25ch" },
        display: "flex",
        justifyContent: "flex-start",
        alignItems: "center"
      }}
      noValidate
      autoComplete="off"
    >
      <TextField
        id="outlined-basic"
        label=""
        placeholder="ddd "
        variant="outlined"
        onChange={onInputChange}
      />
      <span style={{
        position: "absolute",
        marginLeft: "52px",
        color: "red",
        fontWeight: "bold",
        display: hideAsterisk ? "none" : "block",
        pointerEvents: "none"
      }}>*</span>
    </Box>
  );
}

This is far from ideal, as the marginLeft value of the <span> element will depend on the size and padding of the text field, and the number of characters in the placeholder. In theory, this could be calculated on each render, and you could extract this logic into a separate component, however, this would only be necessary if you plan on having dynamic placeholder values or encountering the same problem in multiple components.

Tomasz Kasperczyk
  • 1,991
  • 3
  • 22
  • 43