Dealing with CSS specificity issues when incorporating material-ui for React into a WordPress plugin

Struggling to integrate material-ui for react in a wordpress plugin due to conflict with wordpress's styling in forms.css file. Looking for a solution that doesn't require complete restyling of material-ui components to override the default styles.

For example:

Here is an example(text has been edited for readability(removed selectors that dont matter and styling):

react jsx:

<div id='ad-campaign-edit' style={modalStyle} className={classes.root}>
            <form
                className={classes.form}
                noValidate
                autoComplete='off'
            >
                <TextField
                    id='ad-campaign-name'
                    className={classes.textField}
                    variant='filled'
                    label='Navn på kampanjen'
                />
                <TextField
                    id='ad-campaign-sub-title-text'
                    className={classes.textField}
                    variant='filled'
                    label='Undertekst'
                />
                <TextField
                    id='ad-campaign-sub-price'
                    className={classes.textField}
                    variant='filled'
                    label='Pris'
                />
                <Checkbox
                    defaultChecked
                    className={classes.textField}
                    color='primary'
                    inputProps={{ 'aria-label': 'secondary checkbox' }}
                />
            </form>
        </div>

forms.css(WP):

input[type="text"], {
   ...
}

generated css from material-ui:

.MuiInputBase-input {
   ...
}

Noting that material-ui generates its css after wordpress's, where forms.css specificity is (0-1-1) and material-ui is (0-1-0).

How can I ensure material-ui styles take precedence without starting from scratch with makeStyles hook? Is it possible to enhance material-ui's specificity globally?

edit: Forgot to add html/jsx edit2: revised specificity understanding.

Answer №1

I managed to get it working, although there are still some kinks to iron out. This solution serves as a good starting point.

To make this work, you'll need to install the npm package found at this link: https://www.npmjs.com/package/jss-increase-specificity

After installation, you must create a <StyleProvider> following the instructions provided here: https://material-ui.com/styles/advanced/#jss-plugins

This is what I implemented:

import { create } from 'jss';
import { StylesProvider, jssPreset } from '@material-ui/core/styles';
import increaseSpecificity from 'jss-increase-specificity';


const jss = create({
    plugins: [...jssPreset().plugins, increaseSpecificity({ repeat: 1 })],
});

export default function App() {
  return (
    <StylesProvider jss={jss}>
      ...
    </StylesProvider>
  );
}

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

What are the steps to troubleshoot and fix the Internal Server Error on Next.Js?

I recently set up a new Next.js app using the command npx create-next-app. After that, I added Sass to my project with yarn add sass and proceeded to run it with yarn dev. To my surprise, I encountered multiple errors in both my terminal and on localhost. ...

Adjusting the width of a select box to match the size of its child table using CSS

Within my Vue application, I've implemented a select box that contains a table component. When the select box is clicked, the table becomes visible in a container. However, I'm facing an issue where I can't dynamically adjust the width of th ...

What is the best way to set up a session in a Next.js project?

I am currently utilizing Next js for my project development. I've successfully crafted a unique signup form within the platform where users can input their email and password, followed by an OTP being sent to their email address for verification purpo ...

Is there a way to attach a file in Mongoose Schema? I tried using String and it worked, but when I tried to use File, I encountered the error "[1]Error: File is not

const mongoose = require('mongoose'); const { Schema } = mongoose; const NoteSchema = new Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'user', }, title: { type: String, required: true, }, attac ...

Creating an HTML element that can zoom, using dimensions specified in percentages but appearing as if they were specified in pixels

This question may seem simple, but I have been searching for an answer and haven't found one yet. Imagine we have an HTML element with dimensions specified in pixels: <div style="width:750px; height: 250px"></div> We can easily resize i ...

Error: The reference property 'refs' is undefined and cannot be read - Next.js and React Application

Here is my code for the index page file, located at /pages/index.js import { showFlyout, Flyout } from '../components/flyout' export default class Home extends React.Component { constructor(props) { super(props); this.state = {}; } ...

Modifying the border hue of Material-UI's Select Component

Here is the Select component I've created using materials-UI <FormControl variant="outlined"> <Select value={this.state.value} onChange = {this.handleChange} className={this.props.classes.select} inputProps = {{class ...

What is the best way to deactivate TextField input when using MUI Autocomplete?

Currently, I have implemented the Autocomplete feature with TextField in my application to serve as a form field input. However, there is one specific case where I want to restrict text input and only allow selection from the dropdown elements. When consi ...

Tips for compiling JSX files for React in Rails 7

In my current project, I have a React component located at javascript/application/components/star_rating.js.jsx. Now, I am trying to implement this component in another part of my JS code with the following snippet: let starRating = <StarRating name={na ...

Angular Material: Enhanced search input with a universal clear button

After searching for a cross-browser search control with a clear button similar to HTML5, I found the solution rendered by Chrome: <input type="search> The code that gave me the most relevant results can be found here. I used the standard sample w ...

Unable to input any text in the field when utilizing the value={} attribute

In my NextJS project, I am working on creating a form to update supplier information. Here is the input field in question: <input type="text" ref={nameDisplayedRef} className='p-2 rounded' name='nameDisplay ...

What causes a neighboring div to change width when a multi-line span is present?

Here is my React code: <InfoWrapper> <InfoCircle> <span>i</span> </InfoCircle> <span className="info-label"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. elit. </span> </InfoWrap ...

search for the compose function in the material table within a react component

When I receive a string array as a response from the API for lookup, it looks like this: ['India', 'Sri Lanka'] I am looking to pass this as a parameter to a Material React table column as a List of Values (LOV) in the following format ...

Using Redux with React for managing Material UI TablePagination

I am struggling to control the navigation of a MaterialUI table page. Currently, I am utilizing the onChangePage property, but it only allows me to move forward through pages and does not provide an option to go back to previous pages. My query is regardin ...

Learn the easy steps to exporting all the pages to CSV format using MUI DataGrid

I'm working with a DataGrid table from Material UI that has over 3000 rows, with a maximum of 50 rows per page. My goal is to export all rows to CSV when I click the export button. Current issue: Only data from the current page is being exported Co ...

The best way to close a swipeable drawer from a different class

I'm feeling a bit puzzled by the explanation of SwipeableDrawer on the Material-ui website. Here's the setup I have: there's a Component called 'Sidebar' that opens a SwipeableDrawer when a user clicks a button on the appbar or swi ...

Steps for mandating the specification of a type parameter for a generic React component

When setting up a new instance of a generic React component, I noticed that the TypeScript type checker automatically defaults to unknown without requiring me to specify the type argument: Ideally, I would prefer if TypeScript prompted for the explicit ty ...

There is a button on my website that uses a small piece of Javascript to post a tweet, but unfortunately, it is not functional on mobile devices

Check out this link to view the demonstration - http://codepen.io/illpill/pen/VbeVEq function sendTweet(message, author) { window.open('https://twitter.com/intent/tweet?hashtags=thequotemachine&text=' + encodeURIComponent('"' + m ...

Email forms without server interaction

Hey there, I'm looking to add a simple "+" or "-" voting form into an email newsletter. // plus button "+" <form action="/email-opinions/" method="POST"> <input type="hidden" value="GSC" name="strainName"> <input type="hidden" value="y ...

Enhancing the appearance of an Angular.js application

On the same page, there are two buttons - one for buying and one for selling. It appears that both buttons share the same HTML instance. This creates a problem when trying to style them individually using classes, ids, or other HTML-targeted selectors, as ...