Tips for transitioning from custom CSS to Material UI's CSS in JS

I came across a project where someone implemented components with custom CSS.

One interesting thing I noticed was a wrapper component, similar to Material UI's Container or just a simple div with applied styles.

export const Container = styled.div`
  position: relative;
  margin: 0 auto;
  margin-top: ${p => p.marginTop ? p.theme.spacing[p.marginTop] : 0};
  width: 100%;
  max-width: ${p => (p.maxWidth && p.theme.screen[p.maxWidth])};
  padding: ${p => p.padding ? `0 ${p.theme.spacing[p.padding]}` : `0 ${p.theme.spacing.sm}`};
  z-index: ${p => p.zIndex && p.theme.zIndex[p.zIndex]};
  background-color: ${p => p.color && p.theme.colors[p.color]};
  border-radius: ${p => p.radius && p.theme.radius[p.radius]};
`;

However, I am having trouble understanding what p.marginTop, p.theme, and others mean.

Now, I would like to simplify this by converting it into a basic div wrapper with styles following the Material UI approach.

Something like this:

const useStyles = makeStyles((theme) => ({
  container: {
    position: 'relative',
    margin: '0 auto',
   // margin-top: ${p => p.marginTop ? p.theme.spacing[p.marginTop] : 0},
    width: '100%',
   // max-width: ${p => (p.maxWidth && p.theme.screen[p.maxWidth])},
  //  padding: ${p => p.padding ? `0 ${p.theme.spacing[p.padding]}` : `0 ${p.theme.spacing.sm}`},
    padding: theme.spacing.sm,
  //  z-index: ${p => p.zIndex && p.theme.zIndex[p.zIndex]},
 //   background-color: ${p => p.color && p.theme.colors[p.color]},
 //   border-radius: ${p => p.radius && p.theme.radius[p.radius]},
  }
}))

Unfortunately, all the commented lines are causing errors as they do not recognize 'p'.

(I managed to find a workaround for the p.theme related values by importing them from a theme.js file, but I'm still confused about p.padding and p.maxWidth)

Could someone please explain this to me?

Answer №1

If you want to customize the material-ui Container component, give this a try:

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

const useStyles = makeStyles(theme => ({
  container: {
    marginTop: "100px",
    position: "relative",
    ...
  },
}));

export default function App(){
    const classes = useStyles();
    return (
        <Container className={classes.container}>
          ...
        </Container>
    )
}

All the styles you defined in useStyles for the Container will be used on the actual component.

If you prefer to create your own custom component, you can do it by creating a new file like this:

import styled from "styled-components";

const CustomContainer = styled.div`
  margin-top: 100px;
  margin-left: 320px;
  margin-right: 40px;

  h1 {
    font-size: 18px;
    display: flex;
    flex-direction: row;
    align-items: center;
    min-height: auto;
    font-weight: 500;
    font-family: "Roboto", Helvetica, Arial, sans-serif;
    margin-bottom: 3px;
    text-decoration: none;
    color: #413e3e;
  }
`;

export default CustomContainer;

Once you've created your custom component, you can import and use it in any of your files as needed.

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

How to set the color of the active button within a group of buttons in React using Material UI

I'm having trouble changing the color of a button that is clicked in Material UI. The first button should be active by default. However, I can't use e.target.name because there is no name attribute in the span created within the Button component. ...

Using Ajax/jQuery in combination with Mongodb

My experience with Ajax/jQuery is fairly new. I am currently working on creating a sample HTML page using Ajax/jQuery to retrieve all customers and search for a customer by ID. Each customer has three variables: ID, firstName, and lastName. I am looking t ...

Error: Required package bootstrap-duallistbox@github:istvan-ujjmeszaros/bootstrap-duallistbox is not found

After running npm install to install packages, I encountered the following error : npm ERR! code ELOCKVERIFY npm ERR! Errors were found in your package-lock.json, run npm install to fix them. npm ERR! Missing: bootstrap-duallistbox@github:istvan-ujj ...

Experiencing Difficulty Integrating MUI into NextJS 13 Application Router Despite Having Followed Tutorials

While configuring my Nextjs 13 App Router with MUI 5, I carefully followed the instructions provided at this link: https://mui.com/material-ui/guides/next-js-app-router/. My code closely resembles the sample code found here: https://github.com/mui/material ...

Resolve the issue pertaining to the x-axis in D3 JS and enhance the y-axis and x-axis by implementing dashed lines

Can anyone assist with implementing the following features in D3 JS? I need to fix the x-axis position so that it doesn't scroll. The values on the x-axis are currently displayed as numbers (-2.5, -2.0, etc.), but I want them to be shown as percentag ...

Creating an Interactive and Engaging 3D Experience on Facebook with the Power of Javascript API

Looking for suggestions on a 3D API in JavaScript that can be used to create immersive applications on Facebook. Is there something similar to this one: ? Appreciate any insights. ...

Recreating the MUI v5 Popper scrolling feature in a CodeSandbox playground

I'm trying to locate the reference code for MUI v5 Popper scroll playground in order to address some issues I'm experiencing with the dynamic arrow within the popper. Unfortunately, the arrow is not behaving dynamically as expected. Click here ...

Having trouble with your website's container not wrapping properly?

I've run into an issue where my container is not wrapping a border around the other elements, only around the header. I checked with validators for both CSS and HTML but there are no errors being shown. Does anyone have an idea what might be causing t ...

How can I design a trapezoid with see-through borders and background?

Using various CSS border tricks, it's possible to create a trapezoid shape. Additionally, setting the border-color to rgba(r,g,b,a) can make it transparent. However, is there a way to create a trapezoid with both transparent borders and background? ...

Showing post response (XMLHttpRequest) on Chrome extension interface instead of Python console

I am currently developing a Chrome extension that sends a post request with information about the specific URL being browsed by the user to Flask (local host). A web scraping process is then carried out on this URL to determine a category based on the obta ...

Stopping unauthorized users from manipulating REST URLs

I am currently exploring methods to prevent an exploit where a user manipulates the URL, specifically in a GET request scenario. The following code represents a route on my Express router that processes incoming requests for a certain collection "A" and re ...

Ways to verify if a string contains a specific template literal in javascript

I attempted to verify this by using the str.includes('${') method as a straightforward approach, but it did not produce the expected results. I found that it also returned strings that didn't contain the specified characters. For instance, ...

``Why is it that the JavaScript code is unable to find the maximum or minimum sum? Let's

function calculateMinMaxSums(arr) { // Custom code implementation let max = Math.max(...arr); let min = Math.min(...arr); let minsum = 0; let maxsum = 0; for (let x in arr) { if (arr[x] != max) { minsum += arr[x]; }; if (arr[x ...

I keep running into errors whenever I try to run npm install in my React JS project. The only way for me to successfully install dependencies is by using npm install --force. How can I go about resolving these

I am encountering this error message while working on my project: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @mui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681b1c11040d1b ...

Defining RefObject effectively in TypeScript

Greetings everyone, I am a newcomer to TypeScript and currently attempting to create a type for a RefObject that is of type HTMLAudioElement. However, I have encountered an error message. The error states: Type 'MutableRefObject<HTMLAudioElement> ...

Error encountered during the building of a Java project using Gradle

I ran into an issue with Git Bash error output (build failed). Despite attempting to resolve it by installing Python as suggested, setting the Python environment variable in IntelliJ, and following other recommendations, I still encounter the same build ...

Issue with hook not updating when invoked inside useEffect

I'm encountering an issue with updating the state after fetching data from my API. The API response seems to be correct, but for some reason, my weatherData-hook is not getting updated and it returns undefined. Can anyone point out what mistake I migh ...

Utilizing AJAX for seamless communication between JavaScript and PHP within a modal dialogue box

I'm struggling with learning how to effectively use ajax. In the project I'm currently working on, I have a chart where I can select different people. Once I click on a person's button, their information gets updated in the database. However ...

Retrieve the content from a textarea and insert it into a different textarea with additional text included

Users can input HTML codes into a textarea named txtar1. A 'generate' button is available; Upon clicking the 'generate' button, the content of txtar1 will be transfered to another textarea named txtar2 with additional CSS code. Here&ap ...

How can I implement a redirect back to the previous query page post-authentication in Next.js 13?

To enhance security, whenever a user tries to access a protected route, I plan to automatically redirect them to the login page. Once they successfully log in, they will be redirected back to the original protected route they were trying to access. When w ...