A step-by-step guide to customizing MUI CSS within a React component that incorporates MUI elements

Here is a custom Reactjs component I created and used in various components:

function CustomSearchBox({ handle, placeholder, inputType, ...props}) {
  return (
        <Box
            sx={{
                display: 'flex',
                alignItems: 'flex-end',
                margin: 1,
                marginTop: 0,
                maxHeight: '30px'
            }}
        >
            <TextField
                sx={{
                    fontSize: '12px',
                    width: '100%'
                }}
                variant={inputType || 'standard'}
                InputProps={{
                    startAdornment: (
                    <InputAdornment position='start'>
                            <SearchIcon
                                sx={{
                                    color: 'action.active',
                                    mb: 0.2,
                                    display: 'flex',
                                    alignItems: 'flex-end'
                                }}
                            />
                        </InputAdornment>
                    ),
                    placeholder: placeholder || 'Search'
                }}
                onChange={handle}
            />
        </Box>
    );
}

I am using this Component in another component

<CustomSearchBox handle={Keyword}/>
. How can I override the CSS for TextField and Box of the CustomSearchBox component without modifying the component itself?

When I inspected the browser, I noticed something like this:

<div class="MuiBox-root css-1uqe0j">...</div>

What is the meaning of css-luqe0j ?

Could someone assist me with this?.

Answer №1

If you prefer not to make any changes to the SearchBox component at all, there are several choices available. One of the most practical options, in my opinion, is to wrap the SearchBox component in a custom styled component that targets elements within the SearchBox itself, like this:

const SearchBoxStyleOverrides = styled("div")({
  ".MuiBox-root": {
    padding: "2rem",
    backgroundColor: "green"
  },
  ".MuiSvgIcon-root": {
    color: "red"
  },
  ".MuiInput-input": {
    backgroundColor: "yellow"
  }
});

export default function YourApp() {
  return (
    <SearchBoxStyleOverrides>
      <SearchBox />
    </SearchBoxStyleOverrides>
  );
}

This will result in: (intentionally made ugly) https://i.sstatic.net/T6C9r.png

Working CodeSandbox: https://codesandbox.io/s/peaceful-dubinsky-wjthtt?file=/demo.js

To address your additional query ("what is css-luqe0j?"), that refers to the dynamically generated css class name for the component -- it's advisable not to use these for styling as they may change frequently.

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

Integrate HTML parsing both inside and outside of an iframe using BeautifulSoup

My current project involves web scraping a real estate listing platform using Selenium, BS4, and Python. The script works by fetching the links to each listing page before proceeding to parse the HTML content of those pages. One key component is a Chrome E ...

Formik integration issue with MUI DatePicker causing error message: "date.isBefore is not a function"

I'm currently creating a form in React using Formik and MUI components. However, I encountered an error that says: date.isBefore is not a function TypeError: date.isBefore is not a function at DayjsUtils.isBeforeDay (http://localhost:3000/static/j ...

Customizing text field color in MaterialUI

I am attempting to change the border color from the default purple to white. Below is the progress I have made so far: const customStyles = makeStyles(theme => ({ darkModeCustomInput: { color: WHITE }, darkModeC ...

Adjusting the text color of cells in a table based on their values using Ruby on Rails

I have a cell within a table that is formatted like this: <td><%= play_result.timestamp.strftime("%H:%M:%S") + ' ' + play_result.status + ':' + ' ' + '[' + play_result.host + ']' + ' ' ...

Mui Select fails to update value when defaultValue is specified

I am using a select component from the MUI React library along with react-hook-form and controller. I have set a default value in the controller to use the reset function, but I am unable to change the value when a default value is set. Everything works ...

Contrasting code splitting and lazy loading techniques in React

I could use some clarification on the term load in this context - does it refer to loading into memory directly or fetching over the network before loading into memory? ...

How to style material-ui input with outlined variant using css

Currently, I am attempting to replicate the material-ui outlined input. The background color and input styles are different, so simply setting the label position to absolute and pushing it up is not working for me. Any suggestions on how to achieve this? ...

What steps can I take to eliminate the warning "Warning: Prop `style` did not match" that appears when I bring in the Image component in Next.js?

Hi there! I'm encountering a warning when trying to import an image using the Image component in nextjs. The warning message reads: Warning: Prop style did not match. Server: "display: block; max-width: 100%; width: initial; height: initial; ba ...

Unable to modify the background image of a div using jQuery

I'm encountering an issue in my script where I tried to implement an event that changes the background-image of a div when a button is clicked, but it's not functioning as intended. Below is the code snippet: HTML <div class="col-md-2 image ...

What is preventing npm sass from compiling properly?

https://i.stack.imgur.com/ekbNW.png While making edits to my code, I've noticed that the sass-compiler isn't indicating any errors (red lines) or successful compilations (green lines). Can someone help me identify where I might be going wrong? ...

Adding CSS code to my index.css file in React is not reflected in my application

I've been following a tutorial on YouTube about reactJS, and the YouTuber recommended importing a CSS file into index.css to properly style the website. However, when I tried copying the CSS code and importing it into both App.js and Index.js, nothing ...

Unable to interact with web element

When using selenium, I have a web element that I want to select. The WebElement.IsDisplayed() method returns true, but I am unable to perform the webelement.click() operation. port_dimension = canvas.find( By.xpath( "//*[local-name() = 'rect'][ ...

Steps to invoke a function repeatedly for an animation

I found this code snippet while browsing a forum post about CSS animations. The question asked if it was possible to create a button that would restart the animation when clicked, even if it is in the middle of playing. They specifically requested no jQu ...

Passing parameters to a custom toolbar in Material-UI Data-Grid. How can it be done?

I have been working on creating a custom toolbar for a datagrid using Material-UI. I referenced the documentation at this link and started from this example: here My goal is to show or hide the toolbar with a transition. Since we can't pass custom pr ...

The battle between dynamic PDF and HTML to PDF formats has been a hot

In my current project, I am developing multiple healthcare industry dashboards that require the functionality to generate PDF documents directly from the screen. These dashboards do not involve typical CRUD operations, but instead feature a variety of char ...

Issue encountered during the installation of a React application: npm error

I recently encountered an issue with my React application while running npm install. The error message I received is as follows: λ npm install > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="127b7e667d607052203c263c27"> ...

What is the significance of the .jpg?t= in the URL?

This webcam image displays the code ?t=1512496926. What exactly does this code signify? Could it be related to time? Is it just a random string of characters? https://i.stack.imgur.com/ZAZMy.jpg ...

Encountering a Next.js TypeScript Build Error related to the Type 'OmitWithTag<InputFormProps, keyof PageProps, "default">' issue

`I am currently working on a project in Next Js using TypeScript. During the build process with npm run build, I encountered the following errors in the terminal: # Type 'OmitWithTag<InputFormProps, keyof PageProps, "default">' do ...

Iterate through and conduct conditional verification

In my project using AngularJS and HTML, I have created a table to display records. I am looking for a way to iterate through the column values and strike through any value in the column that meets a certain condition. For example, in the demo provided her ...

What is the best way to disregard all pathNames and display my index.php file directly from the root of my website?

After a user clicks on a navigation link on my website, the page is loaded into a content window within the same page using JavaScript. I then utilize HTML 5 to modify the URL and create a history entry, resulting in a URL resembling the one mentioned (). ...