How do I add an svg icon to Material ui helper text generated by Formik and Yup

Viewed 361

In my React form I am using Formik, Yup and Material ui form and textfield:

import { TextField } from '@material-ui/core';

for my E-mail form.

When I blur out the field it's generating the following HTML:

<p class="MuiFormHelperText-root MuiFormHelperText-contained Mui-error">This field is required.</p>

How do I add an svg icon to this helper text?

For example a React component <HelperText icon={MyIcon} />, is that possible?

1 Answers

You can add the svg with css class from the global styles.css file, it is not a best practice but it's a nice workaround if there is no other solution for this situation. Similarly easy to using SVG as an img, you can use it in CSS as a background-image. for example:

.MuiFormHelperText-root MuiFormHelperText-contained Mui-error {
  display: block;
  text-indent: -9999px;
  width: 100px;
  height: 82px;
  background: url(example.svg);
  background-size: 100px 82px;
}

Notice we set the background-size to the size of the logo element. We have to do that otherwise we’ll just see a bit of the upper left of our much larger original SVG image. These numbers are aspect-ratio aware of the original size. But you could use a background-size keywords like contain if you want to make sure the image will fit and can’t know the parent image will be of the exact right size.

Related