How would I display an image inside a TextField as if it was part of the text, like an InputAdornment just not to either side, but at the beginning of the TextField.
and not next as an icon next to the text input area which is what InputAdornment does (e.g., not like a search icon next to a query field)?
Only way I can think of is just placing the image above the TextField but I found this made it not obvious that the image is part of the input.
I've looked through the documentation but there doesn't seem to be an obvious way of accomplishing this.
Thank you so much in advance!
CodePudding user response:
The comments on your question are partially correct. You can't reasonably edit the actual <input>
without losing functionality, but the Textfield
component is not just an <input>
and is composed of multiple elements that can contain/display an image.
Since no MUI version was specified, I'll assume that you're using latest. (This can also be accomplished with the MUI 4 TextField
using the old makeStyles
function.)
You can change the placement of the TextField
startAdornment
with a few changes to the underlying CSS. Essentially, you can change the default flex-direction
from row
to column
and then finesse the gutters to your liking:
<TextField
id="input-with-icon-textfield"
label="TextField"
variant="outlined"
sx={{
".MuiOutlinedInput-root": {
paddingTop: "1rem",
flexDirection: "column"
},
img: {
paddingRight: "1rem"
}
}}
InputProps={{
startAdornment: <img src="https://via.placeholder.com/180x150/200" />
}}
placeholder="Enter image caption..."
/>
Which produces this:
Working example: https://codesandbox.io/s/inputwithicon-material-demo-forked-tyx7y?file=/demo.js:139-580
CodePudding user response:
You can select the native input element produced by the library and place a background image on it. You would then define a background-position-(x|y)
to adjust the image placement. To alter the text position accordingly, you would move the cursor around inside the field by specifying the padding
or text-indent
property.
Below background positions 5px 6px
for x and y placement is set at the end of the background
property respectively.
input[type='text'][class^='MuiInput'] {
background: url(https://dummyimage.com/20/00ff00/000) no-repeat 5px 6px;
padding-left: 10px; /* or */ text-indent: 10px;
}