unicorns101
unicorns101

Reputation: 89

React Material UI TextField Styles Not Working

I'm trying to style the TextField API provided by Material UI (found here), however, for some reason, the styling is not being applied to the component. When I render it on a webpage, it's shown as in its default form. I would greatly appreciate any help on this. Here is my code.

interface CustomEmptyFieldProps {
usernameOrPass: string,
}

const baseMuiOutlineInputSizeAndPosition = {
borderRadius: 8,
width: '328px',
height: '40px',
};

const baseTextFieldSizeAndPosition = () => (
{
    "& label:not(.Mui-focused)": { // Label in center of TextInput
        marginTop: '-8px',
    },
    "& label:.Mui-shrink": { // Label in center of TextInput
        marginTop:'-8px',
    },
    width: '328px',
    height: '40px'
}
);

const useTextFieldStyles = (isTypedIn: boolean) => (
makeStyles({
        "& label.Mui-focused, label:not(.Mui-focused)": { color: TextFieldColours.error.label },
        "& .MuiOutlinedInput-root": {
            "& fieldset": { borderColor: TextFieldColours.error.border, },
            "&:hover fieldset": { borderColor: TextFieldColours.error.border, },
            "&.Mui-focused fieldset": { borderColor: TextFieldColours.error.border },
            ...baseMuiOutlineInputSizeAndPosition,
        },
        ...baseTextFieldSizeAndPosition, 
})
);



const EmptyTextField = (props: CustomEmptyFieldProps) => {
const {
    usernameOrPass,
} = props; 
const inputLabel = "VolunteerHub " + usernameOrPass; 
const errorMessage = "Please enter your VolunteerHub " + usernameOrPass; 

const textFieldStyles = useTextFieldStyles(false);
return (
    <div>
        <TextField
            classes={{ root: textFieldStyles, }}
            placeholder={inputLabel}
            id="outlined-error-helper-text"
            defaultValue=""
            helperText={errorMessage}
            variant="outlined"

        />
    </div >
);
}

Upvotes: 0

Views: 2208

Answers (1)

Viet
Viet

Reputation: 12779

Not sure about the way you declare your useTextFieldStyles. Here is how I would usually do:

const useTextFieldStyles = makeStyles(() => ({
  root: {
    "& label.Mui-focused, label:not(.Mui-focused)": {
      color: TextFieldColours.error.label
    },
    "& .MuiOutlinedInput-root": {
      "& fieldset": { borderColor: TextFieldColours.error.border },
      "&:hover fieldset": { borderColor: TextFieldColours.error.border },
      "&.Mui-focused fieldset": {
        borderColor: TextFieldColours.error.border
      },
      ...baseMuiOutlineInputSizeAndPosition
    },
    ...baseTextFieldSizeAndPosition
  }
}));

Working sample: https://codesandbox.io/s/runtime-sky-x14vr?file=/src/App.tsx:647-1173

Upvotes: 1

Related Questions