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.