Exploring Material-UI: Leveraging makeStyles and CSS-In-JS for customizing library component styles

I'm currently utilizing Material-UI to construct a form using makeStyles and CSS-In-JS for styling purposes. I have a form component from the Material-UI library that I want to style according to my needs. My main focus is on how to address classes originating from the library's form element and override their styles.

Below is your reference, showcasing the form and the specific Material-UI class that you aim to modify (the before tag of the form's initial text input field):

https://i.sstatic.net/FQ1iY.png

The objective is to alter the border-bottom property of the text field. Here's what I've tried so far. Pay attention to the underline class in the CSS and the first text input of the form:

const useStyles = makeStyles((theme) => ({
    root: {
      display: 'flex',
      width: '100%',
      display: 'flex',
      alignItems: 'center'
    },
    container: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh'
    },
    paper: {
        padding: theme.spacing(2),
        display: 'flex',
        justifyContent: 'center',
        color: 'snow',
        background: 'salmon'
    },
    form: {
        background: 'salmon',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'flex-start',
        height: '50vh',
        width: '50%'
    },
    customInput: {
        background: 'black'
    },
    underline: {
        '&:before': { 
            borderBottom: '10px solid green'
        },
      },
  }));
  
  export default function FormOne() {
    const classes = useStyles();

    return (
    <Grid container className={classes.container}>
        <Grid item xs={12} md={6}>
            <Paper elevation="5" className={classes.paper}>
                <Formik
                    initialValues={{
                    email: '',
                    password: '',
                    }}

                    validate={values => {
                        const errors = {};
                        if (!values.email) {
                            errors.email = 'Required';
                        } else if (
                            !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)
                        ) {
                            errors.email = 'Invalid email address';
                        }
                        return errors;
                    }}

                    onSubmit={(values, { setSubmitting }) => {
                    setTimeout(() => {
                        setSubmitting(false);
                        alert(JSON.stringify(values, null, 2));
                    }, 500);
                    }}
                >
                    {({ submitForm, isSubmitting }) => (
                        <Form className={classes.form}>
                            <Field
                                component={TextField}
                                name="email"
                                type="email"
                                label="Email"
                                fullWidth="true"
                                variant="filled"
                                size="small"
                                color="primary"
                                className={classes.underline}
                            />
                            <br />
                            <Field
                                component={TextField}
                                type="password"
                                label="Password"
                                name="password"
                                fullWidth="true"
                                variant="filled"
                                size="small"
                                color="secondary"
                            />
                            <br />
                            <Field
                                component={TextField}
                                type="password"
                                label="Password"
                                name="password"
                                fullWidth="true"
                                variant="filled"
                                size="small"
                                color="primary"
                            />

                            {isSubmitting && <LinearProgress />}
                            <br />

                            <Button
                                variant="contained"
                                color="primary"
                                disabled={isSubmitting}
                                onClick={submitForm}
                                className={classes.button}
                                >
                                Submit
                            </Button>
                        </Form>
                    )}
                </Formik>
            </Paper>
        </Grid>
    </Grid>
    );
  }

In general, this method works well when styling custom elements. By incorporating const classes = useStyles(); within my function, I can use className={classes.nameOfClass} on the element and target it through makeStyles for styling. However, this approach does not seem to work smoothly when trying to override classes from the Material-UI library.

If you have any insights on how to pinpoint .MuiFilledInput-underline:before in makeStyles and customize its styles effectively, I would greatly appreciate your guidance!

Answer №1

<Field styles={{ underline: styles.underline }} />

and

underline: {
  '&:before': {
    borderBottom: '10px solid green',
  },
},

Visit the official documentation for detailed information on how to target specific elements within components.

Answer №2

If you follow the advice of @hotpink, you'll only be changing the style of the element in that specific component. However, there is a more efficient way to apply these changes globally throughout your project:

const theme = createMuiTheme({
  overrides: {
    MuiButton: {
      root: {
        fontSize: '1rem',
      },
    },
  },
});

In the example above, we are adjusting the css for the global class by overriding the root class from the MuiButton element. This will ensure that all buttons have their fontSize set to 1rem. To find out more about the classes used in components, refer to the component API page like this example

For comprehensive documentation and tutorials, visit here, and make sure to acquaint yourself with using the ThemeProvider here

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

I'm running into an issue with my React component where it is rendering before the state is set, causing it to fail. Is there a

Is it possible for me to achieve what I've been attempting for the past week? I feel like I'm so close, yet still can't quite reach my goal. Could it be that what I'm trying to do is impossible? I am using reactjs and next js (although ...

The dropdown menu is extending outside the header in a right-to-left (RTL) direction

I have implemented the jQuery code below to prevent the dropdown from extending beyond the header area. It works perfectly in the normal LTR version. However, I need a solution for the RTL version. How can I achieve this? jQuery $('.primary-menu .dr ...

What is the best way for me to use a ternary operator within this code snippet?

I'm in the process of implementing a ternary operator into this snippet of code, with the intention of adding another component if the condition is false. This method is unfamiliar to me, as I've never utilized a ternary operator within blocks of ...

What is the best way to apply fill to SVG using Tailwind CSS?

I tried using the code provided, but unfortunately, I was unable to Override the fill. The issue seems to have been resolved, but can someone help me achieve this using tailwind CSS? <div className=""> <svg className="text- ...

ReactJS form submissions failing to detect empty input values

My goal is to use react to console.log the input value. Below is the code I've created: import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component{ constructor() { super(); this.proce ...

What is the correct method for passing derived information between functions that are declared within a functional component in a React application?

What is the best way to efficiently share computedData between functions like getSomeMessage and getAnotherMessage import React from "react"; const SOME_CONST = 10; function Component(props) { const getComputedData = () => { const { prop } = ...

Iterating through an SVG path multiple times

If I have the arrow below and I want to place it at various locations within the svg: <svg width="400" height="400"> <path transform="translate(150,100)" fill="black" d="M 0.5,0.5 l-100,0 -25,20 25,20 100,0 z" /> <path transform="translate( ...

Ways to resolve the error "Uncaught TypeError: data.map is not a function"

Currently developing an app using reactJS and encountering the following error in the console when using the map function: TypeError: data.map is not a function. Despite successful API data calling as confirmed by console.log, the error persists when tryin ...

Issue with React not displaying JSX when onClick Button is triggered

I've recently started learning React and I'm facing a problem that I can't seem to figure out. I have a basic button, and when it's clicked, I want to add another text or HTML element. While the console log statement is working fine, th ...

Steps for displaying a deeply nested array and string within an object that is nested further in an array

I've been troubleshooting an issue in my Next.js code where I'm trying to render data called items. My goal is to display the descriptions in an array as a list and display the description that is a string as it is. However, I cannot use the map ...

Enhance typescript interfaces with third-party library components in React.js

As a newcomer to typescript, I am in the process of converting my existing react project to use typescript. After changing my files to tsx, I encountered several errors which I managed to resolve except for one type-related issue that I couldn't find ...

Move content off the screen using CSS3 translation

Throughout various projects, I have encountered the need to make elements on a webpage translate out of view (essentially making them fly out of the document). The idea was that by simply adding a class to the element, the CSS would take care of the animat ...

Implementing a parallax scroll effect using CSS and dynamically updating the background-position value with JavaScript

How can different Y position percentages be dynamically assigned to multiple layered background images in CSS using JavaScript so that they update as the page scrolls? <style> body { background-image: url(img/bg-pattern-01.png), ur ...

Unusual predicament encountered while using Flow type validation

I've encountered a puzzling situation in my React app while trying to integrate Flow's typechecking. I'm struggling to make everything work smoothly. Here is the relevant code snippet: // @flow export const UPDATE_SESSION_PROP: string = &ap ...

Using CSS to style the last element in a set of dynamic content

I am currently working on targeting the last element in a dynamically generated content set. For instance, here is an example of how the generated content appears: <div class="block"> <div class="block-inner"> <div class="box"> ...

Is there a way to place the icon on the right side of the @mui/Chip component?

Currently, I am working with MUI version 5.15.0. I have a component called Chip, and my goal is to display the icon after the label on the right side. I attempted to use the CSS rule - .MuiChip-icon{ order:1 }, but it resulted in too much spacing. Additio ...

Is there a way to change the color of just the most recently clicked anchor element <a>?

I have a sidebar with anchor elements (Link 1,2,3 in my HTML). I want the text color of these anchors to change when clicked. Additionally, I need only one anchor element to be colored at a time, meaning the previous one should return to its normal color. ...

Switch the position of the checkbox label to the left in a customized Bootstrap checkbox

I am struggling with adjusting the label position for my checkbox. Here is my code: <div class="custom-control custom-checkbox custom-control-inline"> <input type="checkbox" id="location" v-model="checkedLocations" value="location" name="c ...

What is the best way to create a clickable image with a box-shadow when a z-index of -1 is applied?

Is there a way to make an image clickable while still retaining the box shadow effect created using CSS3? Currently, I have set the z-index of -1 for the img tag to apply the box shadow. However, this makes the image not clickable when an href tag is added ...

Blueprint CSS is causing a padding problem

This piece of code is perfectly styled with blueprintcss: <div class="container"> <div class="span-12" style="background-color : cyan"> Hello </div> <div class="span-12 last" style="background-color : green"> Bye </div& ...