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

What is the process for submitting a form in Laravel 5 with ajax?

Struggling with understanding how to create an ajax post in Laravel. I would like to display errors using jQuery after validation, but I'm unsure about accessing the object sent to my controller and what needs to be 'returned' in the control ...

Having trouble with vendor CSS not being recognized during brunch compilation

I am currently exploring the use of Pure.css in my application. After installing it via npm, I have configured my brunch-config.js as follows: stylesheets: { joinTo: { 'app.css': /^app/, 'vendor.css': /^(?!app)/ } } At thi ...

Set up an event listener for a specific class within the cells of a table

After spending the last couple of days immersed in various web development resources, I find myself stuck on a particular issue. As someone new to this field, the learning curve is quite steep... Let's take a look at a single row in my project: < ...

Using JavaScript to set a form via a parameter in the URL

Is there a way to dynamically change the SetForm based on a parameter in the URL, such as radio.php?land=form2? I tried doing it this way but it doesn't seem to work. However, when I do it manually via the menu, it works. This is my first time attemp ...

The React application is persistently sending a stream of HTTP requests

Currently, I have a web page that retrieves and displays data from a MongoDb using an API. Users can make modifications to the data on this page, causing it to refresh with the updated information. However, upon inspecting the network requests, I noticed t ...

what can prevent a React component from re-rendering?

Being a novice in the realm of React, I find myself with a perplexing query. Within my application, I have two distinct components - the parent component named Goals and its child, EditGoal. The Goals component functions to display all goals, while the Edi ...

What is the best way to send my Array containing Objects to the reducer using dispatch in redux?

I'm currently facing an issue where I can only pass one array item at a time through my dispatch, but I need to pass the entire array of objects. Despite having everything set up with a single array item and being able to map and display the data in t ...

Should position: absolute; be utilized in asp.net development?

I am just starting out in web development Would it be a good idea to utilize position: absolute; for controls? If not, can you explain why? ...

What is the origin of the libraries found in npm-shrinkwrap that do not match the packages listed in package.json?

I'm puzzled by the presence of `express` in my `npm-shrinkwrap` file as a main dependency. Despite this, `express` is not listed as a dependency in my `package.json` file. I can't find any usage of it in my project. It's not included a ...

Products failing to appear in shopping cart

I'm facing an issue with my React Redux Cart setup where items are added to the cart state using the addItem action, but they do not appear on the Cart page. Challenge: After adding items to the cart through the addItem action, I can see the state u ...

Why does "react-hot-loader/babel" cause issues in my build process?

After incorporating "react-hot-loader/babel" into my .babelrc file, I am encountering issues with my React components. In particular, the code snippet in question is as follows: export default class Editor extends React.Component { componentDidMount ...

I require the capability to retrieve JSON data from beyond the confines of the function

After searching, I was unable to locate it. In my possession is a javascript file and a separate file named data.json. data.json { "today": [ { "id": 1, "title": "Note 1", "date": "21.05.2019", "text": "Lorem ipsum dolor sit ...

Are the commands overlapping?

Currently, I am in the process of developing a dynamic discord chat bot using JavaScript and node.js. One of my goals is to implement a specific command without interfering with an existing one. The bot functions flawlessly across all servers where it is ...

Can a synchronous loop be executed using Promises in any way?

I have a basic loop with a function that returns a Promise. Here's what it looks like: for (let i = 0; i < categories.length; i++) { parseCategory(categories[i]).then(function() { // now move on to the next category }) } Is there ...

Angular Delight: Jaw-Dropping Animation

After setting up my first Angular project, I wanted to incorporate Angular Animations to bring life to my content as the user scrolls through the page. I aimed to not only have the content appear on scroll but also implement a staggering animation effect. ...

Utilize a button within a form to add additional variables to a URL that already contains variables from a separate form

I operate a website that features a search bar and checkboxes for adding variables to the URL: term = "test" variable1=1 url/search?term=test&variable1=1 After completing the initial search, I have additional forms on the left side of the page with m ...

Enhancing HTML through Angular 7 with HTTP responses

Sorry to bother you with this question, but I could really use some help. I'm facing an issue with updating the innerHTML or text of a specific HTML div based on data from an observable. When I try to access the element's content using .innerHTM ...

The method of importing overrides in Storybook

My component 'ReportWrapper' is structured as shown below. It imports 'getReportData', which asynchronously returns data. import { getReportData } from "../dataFecther"; export const ReportWrapper = ({ query }) => { con ...

When attempting to upload a file using ajax, the $_FILES variable in PHP came

I am facing an issue with uploading images via AJAX where my PHP is not receiving the AJAX post. function handleFileSelect(evt) { files = evt.target.files; // FileList object $('.thumb-canvas' + filesId).css('display','bl ...

How can I show PHP retrieved data in separate text areas?

Struggling to retrieve values from the database? Simply select an employee ID using the 'selectpicker' and watch as the corresponding name and salary are displayed in the textarea. So far, I've managed to set up the following HTML Code: &l ...