Material Form Field and TextFieldRoot overwrite theme with useStyles / jss

Viewed 45

How do I override Material themes for FormControl? It is usually html parent above a Textfield. I want the margin bottom to be 8px, instead of 4px. Below is not working. Currently using MUI version 4

enter image description here export const useProcedureTableStyles = makeStyles({

  overrides: {
    '& .MuiTextField-root': {
      marginBottom: '8px',
    },
  },
  textField: {
    height: '31px',
  },


<TextField
  {...params}
  margin="dense"
  value={listItem}
  error={listItem.duplicateFlag}
  InputProps={{
    ...params.InputProps,
    style: { padding: 0 },
    className: procedureStyles.overrides,
    classes: {
      input: procedureStyles.textField,
    },
  }}
/>

Researching this resource: material-ui overwrite theme with useStyles / jss

2 Answers

Below is a simplified version of the html structure shown in your screenshot:

<div class="MuiFormControl-root MuiTextField-root">
   <div class="MuiOutlinedInput-root">
      <input type="text" class="MuiOutlinedInput-input"/>
   </div>
</div>

You are passing procedureStyles.textField via the input key of the classes prop in InputProps. That targets the innermost input element (and I assume that is working as intended). That input element can also be targeted using the className property of inputProps (lowercase i).

You are passing procedureStyles.overrides via the className property of InputProps. InputProps targets the second div in the structure above (the one with class="MuiOutlinedInput-root"), and then your margin bottom styles are being applied to any descendants of the div that have a class of MuiTextField-root. Since the div you want to target is an ancestor of that second div and not a descendant, your styles have no effect.

To target the first div in that structure, you can use the className prop directly on TextField. It would also be equivalent to use the root key of the classes prop directly on TextField.

Here's a working example:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";

const useStyles = makeStyles((theme) => ({
  overrides: {
    marginBottom: "8px"
  }
}));

export default function BasicTextFields() {
  const classes = useStyles();

  return (
    <>
      <div>Something before to demonstrate top margin</div>
      <TextField
        id="outlined-basic"
        margin="dense"
        label="Outlined"
        variant="outlined"
        className={classes.overrides}
      />
      <div>Something after to demonstrate bottom margin</div>
    </>
  );
}

Edit override FormControl styles of TextField

Do this in your Material-UI theme:

overrides: {
  MuiFormControl:{
    marginDense:{
      marginBottom:'8px'
     }
   }
 }
Related