Reputation: 2116
I am learning Material-UI for the first time. I want to customize the TextField of material UI. I am able to change the style of the textfield when it is not selected, I am unable to change its style when it is focused.I am using ThemeProvider
to inject the style into component. I have tried this code
import React from "react";
import Checkbox from "@material-ui/core/Checkbox";
import TextField from "@material-ui/core/TextField";
import {
createMuiTheme,
makeStyles,
createStyles,
Theme as AugmentedTheme,
ThemeProvider
} from "@material-ui/core/styles";
import { orange, blue, green } from "@material-ui/core/colors";
const useStyles = makeStyles(theme =>
createStyles({
root: {
color: green[900],
"&.Mui-focused": {
border:"2px solid blue",
}
},
})
);
function CustomCheckbox() {
const classes = useStyles();
return (
<TextField
variant='outlined'
classes={{
root:classes.root,
}}
/>
);
}
const theme = createMuiTheme({
});
export default function CustomStyles() {
return (
<ThemeProvider theme={theme}>
<CustomCheckbox />
</ThemeProvider>
);
}
Question:
How to change style of TextField on focus? Help would be appreciated
Upvotes: 5
Views: 23743
Reputation: 15146
To customize MUI TextField input element
's border styles:
const useStyles = makeStyles(theme =>
createStyles({
root: {
color: green[900],
"& .MuiOutlinedInput-root": {
"& fieldset": {
borderColor: "rgba(0, 0, 0, 0.23)" // default
},
"&.Mui-focused fieldset": {
border: "2px solid red" // focus
}
}
}
})
);
Try it online: https://codesandbox.io/s/style-text-field-3unyl
The accepted answer by the way:
Upvotes: 7
Reputation: 62556
Actually what you are probably after is setting the className of the InputProps
:
<TextField variant="outlined" InputProps={{ className: classes.root }} />
If you want to also remove the border of the fieldset (or only control that border) you can set it with this:
const useStyles = makeStyles(theme =>
createStyles({
root: {
color: green[900],
"&.Mui-focused": {
border: "2px solid red",
'& .MuiOutlinedInput-notchedOutline': {
border: 'none'
}
}
}
})
);
You can find a working example here: Check the following: https://codesandbox.io/s/style-text-field-htbem?file=/src/App.js
You can find more information about the different classes MUI is using with the Input component here: https://material-ui.com/api/input/#css
Upvotes: 6