A rather strange problem that I have been trying to solve for a long time but without success.
Essence: to style the TextField (which is intended for site search)
Now in more detail: I styled the TextField in such a way that the borders of the empty field (inactive) would be black, and also if the field has any value, so that the borders of the field would be blue (even if there is no cursor on the field at the moment)
const CssTextField = withStyles({
root: {
'& .MuiOutlinedInput-root': {
'& fieldset': {
borderColor: 'black',
},
'& input:valid fieldset': {
borderColor: 'blue',
borderWidth: 2,
},
},
},
})(TextField);
But I need to add a cross icon to this field so that the user can delete the values entered (for this I used endAdornment). As soon as I add the icon (CloseButton), the styles don't work. And the blue color for the inactive non-zero field does not apply. Remarkably, if I add a any string (instead of a CloseButton), everything works.
I can't figure out why the style changes when adding this component. Can you advise me?
CodePudding user response:
It's hard to say without me running it but its probably because you are using the
css selector, which is a bit brittle.
The
selector targets the immediate fieldset
sibling of input
. I'm stretching a bit here, but its probably that as soon as you add the endAdornment
, material ui is changing the DOM structure such that fieldset
is no longer the first sibling after input
.
This makes sense with the text-only working since this text node does not count as a sibling because text by itself is not an element unto itself as far as CSS is concerned, which has the affect of "skipping" over it.
The solution might be to use the ~
selector which targets all siblings.
const CssTextField = withStyles({
root: {
'& .MuiOutlinedInput-root': {
'& fieldset': {
borderColor: 'black',
},
'& input:valid ~ fieldset': {
borderColor: 'blue',
borderWidth: 2,
},
},
},
})(TextField);
If this doesn't work, add a screenshot of the rendered DOM with the endAdornment
and I will try to help.