Modify one individual css style / tag

Currently, I have a large React application that is utilizing Material UI 4.3.0.

I attempted to remove the margin-top style of label + .MuiInput-formControl within a select Mui component. To achieve this, I used the 'overrides' tag in my App.js file, similar to how I had done it previously:

const theme = createMuiTheme({
overrides: {
 MuiInput: {
  formControl: {
   "label + &": {
    marginTop: "0",
   }
  }
 }
},
...
}

This approach worked as expected, but it caused issues with every other instance of the same component. Now, I am struggling to properly override the default styles in my current working file where I intend to make the margin change. What would be the correct method to achieve this?

I've attempted overriding with classes without success, tried using

const styles = theme => ({ overrides.... etc
as mentioned in the example above, and experimented with inline styles as well.

I understand there must be a proper way to handle this situation, but my lack of experience has me stumped. One workaround that worked, albeit incorrectly, was wrapping the component in a div and applying negative margins, yet I am keen on resolving this correctly for future use as well.

Thank you!


Edit: Here is the component I am attempting to style

renderFormats(){
 const { formats } = this.state;
 let formatsDOM = undefined;
 if(formats !== undefined && this.state.selectedFormat !== undefined){
  formatsDOM =
   <Select
    value={this.state.selectedFormat}
    onChange={this.onExportChange.bind(this)}
    disabled={!this.state.customFormatIsSelected}                                    
    inputProps={{
    name: 'Format',
    id: 'FormatInput',                                                           
    }}                                                                               
   >
   {formats.map( format => this.renderFormatEntry(format))}                         
  </Select>                                                                            
 }
return formatsDOM;                                                                           
}

Answer №1

If you are utilizing the TextField component, then it is necessary to define the formControl class through the InputProps. If you opt for the more granular components (FormControl, InputLabel, and Select) explicitly, a custom Input component (referred to as InputNoMargin in this context) with the specified formControl class is required. You will then need to specify that component using the input property of the Select component.

An illustration below demonstrates how this styling can be applied to a text input TextField, a select TextField, and a "composed" Select utilizing the lower-level components.

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import Input from "@material-ui/core/Input";
import Select from "@material-ui/core/Select";

const useStyles = makeStyles({
  formControl: {
    "label + &": {
      marginTop: 0
    }
  }
});

const currencies = [
  {
    value: "USD",
    label: "$"
  },
  {
    value: "EUR",
    label: "€"
  },
  {
    value: "BTC",
    label: "฿"
  },
  {
    value: "JPY",
    label: "¥"
  }
];

const InputNoMargin = props => {
  const inputClasses = useStyles(props);
  return <Input {...props} classes={inputClasses} />;
};
export default function TextFields() {
  const inputClasses = useStyles();
  const [values, setValues] = React.useState({
    name: "Cat in the Hat",
    currency: "EUR"
  });

  const handleChange = name => event => {
    setValues({ ...values, [name]: event.target.value });
  };

  return (
    <form>
      <TextField
        id="standard-name"
        label="Name"
        value={values.name}
        InputProps={{ classes: inputClasses }}
        onChange={handleChange("name")}
        margin="normal"
      />
      <br />
      <TextField
        id="standard-select-currency"
        select
        label="Select"
        value={values.currency}
        onChange={handleChange("currency")}
        InputProps={{ classes: inputClasses }}
        helperText="Please select your currency"
        margin="normal"
      >
        {currencies.map(option => (
          <MenuItem key={option.value} value={option.value}>
            {option.label}
          </MenuItem>
        ))}
      </TextField>
      <br />
      <FormControl>
        <InputLabel htmlFor="composed-select">Composed Select</InputLabel>
        <Select
          value={values.currency}
          onChange={handleChange("currency")}
          inputProps={{ id: "composed-select", name: "composed-select" }}
          input={<InputNoMargin />}
        >
          {currencies.map(option => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </form>
  );
}

https://codesandbox.io/s/textfield-and-select-input-classes-0xn2b?fontsize=14

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a logo that scales seamlessly across different web browsers while maintaining responsiveness through

I am working on making this logo align perfectly with all screen resolutions and browsers, while ensuring it stays at the exact center (both vertically and horizontally) of the #container. If the resolution drops below 320px, I want the company name to dis ...

It seems that restarting the server multiple times is necessary to ensure that mui styles properly integrate with nextjs

After referencing the Nextjs setup with MUI, I have successfully implemented the styles. However, I encountered an issue when trying to override MUI CSS using makeStyles - I noticed that I must repeatedly restart the server in order to see the changes re ...

Is it possible to center an anchor link in React JS using Webpack, Sass, and Bootstrap 4?

Recently, I started delving into React JS and Webpack but encountered a perplexing issue. My goal is simple - to center an anchor link on the screen. However, despite trying various methods like inspecting the element, removing inherited styles, setting wi ...

Jekyll adjusting the starting line of code snippet formatting

Currently, I'm in the process of setting up code highlighting for my blog using Jekyll and Pygments. However, I'm facing an issue where the first line of every code snippet seems to be slightly offset. To create a gutter effect, I'm utilizin ...

Issues arising with VueJS array props when integrating Bootstrap

I am attempting to display two divs next to each other while iterating through props (which are essentially an array) in VueJS. When I have just a single element, everything functions properly. However, as soon as I include the v-for directive, the element ...

Can the variable name within a function be retrieved?

How can I retrieve the variable name (user_name1 or user_name2) from a sample function (GetUserName()) within itself? This variable name is required to create an object with the same name on the server side for data synchronization purposes. function GetU ...

What could be the reason behind Strapi v4 only displaying the initial 25 articles? Discussing Next.js and React

I've encountered a peculiar bug while working with Strapi v4. The technology stack being used is React and Next.js I've set up a dynamic pagination system with the format /page/[slug]. It's functioning almost perfectly, except for one majo ...

Activate the search feature in select2 to allow multiple selections

I'm looking for a way to incorporate a search box into my multi-select fields using select2. Oddly enough, while the search boxes show up as expected in single-select fields, applying the same select2() function to a multi-select field doesn't s ...

Stacking the FontAwesome icons on a PrimeNG button

I've been experimenting with various methods to incorporate stacked icons on a pButton in Primeng, but I haven't had any success. Does anyone have a solution that doesn't result in the button being twice its normal height? Here are a couple ...

Tips to prevent browser from freezing while creating a large number of HTML elements

I am currently utilizing Selection.js to develop a customizable grid on my website. To make this work effectively, I need a specific number of div elements to establish the selectable area. In my scenario, I generate all the divs using a for loop and then ...

Navigate to a particular section in the webpage

There are a few div elements with the class .posts that each have an attribute data-id which corresponds to the ID in a MySQL database. <div class="posts" data-id="1"></div> <div class="posts" data-id="2"></div> If I want to scrol ...

Enhance CKEditor with Linked Select Boxes Plugin

I have ventured into writing a CKEditor Plugin and have grasped the basic concepts. For instance: CKEDITOR.dialog.add( 'addDocumentGroupDialog', function ( editor ) { return { title: 'Link to a document group', min ...

Exploring the power of data-callbacks in VueJS

For instance, if we have <div data-callback="recaptchaCallback"></div>, the recaptchaCallback function will run as shown: <script> function recaptchaCallback() { alert('OK'); } </script> The code above functions prop ...

Getting a single item from nested objects within arrays

Having retrieved data from an open API, I encountered an issue when trying to display an image in my browser. The Images array contains 3 image URLs, and despite using the map method on arrays, calling the first object [0] did not yield the desired result. ...

Using JavaScript to assign one object to another object

I am facing an issue where I am trying to assign the local variable UgcItems to uploadedItems, but when I attempt to return the value, it shows as undefined. If I place the console.log inside the .getJSON function, then I get the expected value. However, t ...

A guide on converting a Javascript datetime to a C# DateTime parameter

In a previous question that I asked on StackOverflow, I mentioned that I was able to retrieve my values successfully as the object was no longer null. The object contains a DateTime property named CreatedOn, which I am sending from JavaScript using new Dat ...

What could be the reason for the inability to install Angular JS 2?

Setting up Angular 2 for experimentation on my VPS has been quite a challenge. The initial steps can be found here. Upon trying the first command: $ npm install -g tsd@^0.6.0 I encountered success. However, the second step led to an error: tsd install ...

Ways to hide the value from being shown

I have integrated jscolor (from jscolor) to allow users to pick a color with an input field. However, I am facing issues in styling it as I'm unable to remove the hex value of the selected color and couldn't find any relevant documentation on av ...

Passing the contents of a datatable as parameters to a PHP script

I am facing a challenge with my datatable that has two columns, "Name" and "Age". After populating the datatable using Ajax, I create a button for each row. The goal is to send the "Name" and "Age" fields of the clicked row to a PHP script, which will then ...

Using the $.ajax function to make requests with CORS restrictions

Having some trouble with an AJAX request. I encountered the following error message: Error: Access is denied This is the jQuery AJAX request I attempted: $.support.cors = true; $.ajax({ url: 'http://testwebsite.com/test', type: "GET" ...