Integrating CSS with Material-UI in a React project: A step-by-step guide

I am currently developing a project using React (along with TypeScript) and the Material-UI library.

One of my requirements is to implement an animated submit button, while replacing the default one provided by the library. After some research, I came across this button on this website, which I successfully integrated into my React application by placing the CSS file in a "styles" folder and importing it into my Button's .tsx file. I converted the HTML code to JSX and now my render method looks like this:

return(
    <button className={`submit-button ${btnState}`} onClick={handleClickOpen}>
        <span className="pre-state-msg">Submit</span>
        <span className="current-state-msg hide">Sending...</span>
        <span className="done-state-msg hide">Done!</span>
    </button>
);

Although the button functions correctly, the issue arises when I import the CSS file as it disrupts other components within the application (particularly affecting the Container component). I suspect this may be related to how Material-UI operates, but I am unsure of how to resolve this.

I understand that Material-UI recommends utilizing CSS-in-JS methodologies such as useStyles hook or withStyles. However, I am uncertain how to adapt the existing CSS file for seamless integration. Additionally, I am unsure if these solutions fully support all CSS features such as element>element selectors or classList.add.

In order to address this concern, is there a way to use the CSS file without causing conflicts? According to this documentation, it should be feasible, though my attempts have been unsuccessful so far. Alternatively, if incorporating pure CSS proves problematic, could the code be converted to CSS-in-JS format allowing for dynamic class manipulation?

Thank you in advance to those taking the time to review and assist with this question.

Answer №1

Converting CSS to JSS, which is utilized by MUI behind the scenes, can be easily achieved by experimenting in the JSS playground and examining the generated CSS. This process is not overly complex and can yield great results. For example:

keyframes short_press {
  to: { transform: rotate(360deg); }
}

.submit-button {
  display: block;
}

.submit-button:hover, .submit-button:focus {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.submit-button > span {
  display: block;
}

.submit-button.animated {

}

The converted version would look like this:

import { makeStyles } from '@material-ui/styles';

let useStyle = makeStyles({
  '@keyframes short_press': {
    to: { transform: 'rotate(360deg)' },
  },
  button: {
    display: 'block',
    '&:hover, &:focus': {
       boxShadow: '0 5px 15px rgba(0, 0, 0, 0.1)',
    },
    '& > span': {
       display: 'block',
    },
    '&.animated': {
      animation: '$short_press 1s infinite linear',
    }
  },});

function YourButton() {
  let css = useStyle();
  return (
    <button className={`${css.button} ${animated ? 'animated' : ''}`}>
      Click
    </button>
   );
}


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

Tips for keeping the DropDown Menu displayed even after moving the cursor away from the targeted element in Material-UI

import React from 'react'; import { makeStyles, Typography, Grid } from '@material-ui/core'; const styles = makeStyles((theme) => ({ root: {}, textStyle: { fontFamily: 'brandon-grotesque-black', tex ...

How can I make an absolutely positioned div slide down from a specific area on the page using jQuery's slideDown() function?

I have a website project in progress where the main image on the homepage is of a house with windows and a door. The idea is that when a user clicks on a window, a <div> should appear with some text. Similarly, clicking on the door should trigger a & ...

Issue with CSS styling on a content slider causing the last picture to display incorrectly

I recently updated a Content Slider and tweaked the styles to my preference. Check out the changes I made on this link. In addition, I included an extra Thumbnail Picture on the right (7th one) along with the Main Picture. Oddly enough, the Slider seems ...

What is the best way to pass an array through router navigate function?

I've searched for a solution in other questions, but nothing has helped me... My goal is to redirect to a URL like this: this.router.navigateByUrl('/products'); I want to pass an array and retrieve it in the component with the active link ...

Can we include an option to display all pages in one row on a single page?

Is it possible to include an option to display all rows alongside the current options of 10, 15, and 100? I've been unable to locate this feature in the documentation: Check out the Codesandbox example: https://codesandbox.io/s/muidatatables-custom-t ...

An animation in CSS where an element moves off the screen to the right in absolute position and then returns from the

I am currently working on a website featuring moving clouds traveling across the screen from left to right. Although I have successfully implemented the animation for the clouds, there is one specific issue that has me stuck. My goal is to display some of ...

Harvesting the local image file

Currently, I have implemented a form that allows users to upload images and crop them. The process flow has been established as follows: 1. User uploads the image 2. Server processes the image and sends it back to the browser 3. User crops the image a ...

What is the process for implementing column filtering in a React data table component?

Currently, I'm showcasing live data on a React data table. While I've implemented a global filter, I now want to include individual filters for each column. ...

Displaying JSON data in a browser using Node.js without the need for refreshing the page

I am currently working on a node.js server that fetches JSON data from an external source and displays it in a browser window. I need assistance in setting up an automatic update every minute to reflect any changes in the JSON without requiring a manual re ...

Having trouble accessing a JavaScript variable in Javascript due to reading null property 'value'

What I Require I am in need of passing a URL variable from an HTML document to a JavaScript file. HTML Snippet <script> var urlParam = "{{ page_param.asy_request | replace('&','&')}}"; urlParam = urlParam.rep ...

The error message "AWS Lambda Node 18: fetch is not defined, please resolve or include global fetch" indicates that

Seeking assistance with calling the Pagespeed Insights API from an AWS Lambda using Node 18. Struggling to make fetch() function properly. Cloudwatch logs indicate the message "inside the try about to fetch," but then nothing else appears. The Lambda con ...

Manipulating Angular and Typescript to utilize the method's parameter value as a JavaScript object's value

I am currently working with Ionic, Angular, and Typescript, attempting to dynamically set the value of a location based on the parameter passed from a method. Here is the relevant code snippet: async fileWrite(location) { try { const result = a ...

Expanding the capabilities of the JQuery submit function

Within my web application, I find myself working with several forms, each possessing its own unique id. To streamline the process, I decided to create a custom handler for the submit event in my JavaScript file: $('#form-name').submit(function(ev ...

Tips for sending JSON data to .js files

I am experiencing an issue here. In locations.php, I have the following code to generate JSON data: <?php $locations = array( array('2479 Murphy Court', "Minneapolis, MN 55402", "$36,000", 48.87, 2.29, "property-detail.html", ...

Access the Express server by connecting to its IP address

Is it feasible to connect to an express server using the server's UP address? If so, how would one go about doing this? (Examples of code snippets would be greatly appreciated) ...

Setting a random number as an id in the constructor in Next JS can be achieved by generating a

What steps can be taken to resolve the error message displayed below? Error: The text content does not match the HTML rendered by the server. For more information, visit: https://nextjs.org/docs/messages/react-hydration-error Provided below is the code i ...

Encountering Typescript errors when trying to destructure a forEach loop from the output of

There are different types categorized based on mimetypes that I am currently working with. export type MimeType = 'image' | 'application' | 'text'; export type ApplicationMimeType = '.pdf' | '.zip'; expor ...

Mobile phone web development using HTML5

I am currently facing an issue with playing sound on mobile browsers. In my code snippet, I have the following: Response.Write("<embed height='0' width='0' src='Ses.wav' />"); While this works perfectly fine on desktop ...

Create a ReactJS page with no pre-generated additional pages

Just ventured into the world of reactjs and created my first app. Now I'm trying to build a production version using the command: npm run build However, all I get is a blank index.html file generated. Why is this happening? I have multiple routes in ...

Retrieving a variable value set within a jQuery function from within an Angular 2 component

In the current project, I am facing a situation where I need to work around and initialize jQuery datetimepicker inside an Angular 2 application (with plans to refactor it later). However, when I assign a datetime value to a variable, I encounter a proble ...