Frank Leal
Frank Leal

Reputation: 206

Material-UI custom required text on TextField

The Component allows you to set if the field is required or not, but I want to change the * symbol for * mandatory field.

Is there any way I can do it?

Upvotes: 4

Views: 4635

Answers (1)

Michalis Garganourakis
Michalis Garganourakis

Reputation: 2930

I can't find anything on their API about it, but you can use ::after pseudo-element on the asterisk's <span> element:

import React from "react";
import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles(theme => ({
  root: {
    "& .MuiTextField-root": {
      margin: theme.spacing(1),
      width: 200,

      "& .MuiFormLabel-asterisk.MuiInputLabel-asterisk": { // these are the classes used from material-ui library for the asterisk element
        "&::after": {
          content: '"mandatory field"' // add your text here
        }
      }
    }
  }
}));

export default function FormPropsTextFields() {
  const classes = useStyles();

  return (
    <form className={classes.root} noValidate autoComplete="off">
      <div>
        <TextField
          defaultValue="My Name"
          required
          id="standard-required"
          label="Name"
        />
      </div>
    </form>
  );
}

Also, here is a working example.

Upvotes: 7

Related Questions