When you first open material-ui cards, there are no default CSS styles applied

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

My cards created using material-UI are displaying strangely when the page loads or re-loads. Initially, they look different with no apparent CSS styling, but after a few seconds, they appear as intended. I'm not sure if this is something on my end or just how Material-UI operates.

import React, { Component } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';

class ImgMediaCard extends Component {
  constructor(props){
    super(props)
  }
  render(){
    return (
      <div className="Cards-div">
      <Card className="Cards">
        <CardActionArea>
          <CardMedia
            component="img"
            alt={this.props.imgAlt}
            height="300"
            image={this.props.imgLink}
            title={this.props.imgTitle}
          />
          <CardContent>
            <Typography gutterBottom variant="h5" component="h2">
              {this.props.title}
            </Typography>
            <Typography variant="body2" color="textSecondary" component="p">
              {this.props.text}
              {this.props.technologies}
            </Typography>
          </CardContent>
        </CardActionArea>
        <CardActions>
          <Button size="small" color="primary">
            Visit
          </Button>
       </CardActions>
     </Card>
   </div>
)};
}

export default ImgMediaCard;

Github repository: https://github.com/Kohdz/port

Answer №1

Finally cracked the code after struggling with it for a while. The solution lies within /pages/_document.js. Two crucial steps were needed: reinstating _document.js to handle the getInitialProps() function and integrating the flush method from styled-jsx.

import React from 'react';
Document, { Head, Main, NextScript } from 'next/document';
{ ServerStyleSheets } from '@material-ui/styles';
import flush from 'styled-jsx/server';
{ createMuiTheme } from '@material-ui/core/styles';
red from '@material-ui/core/colors/red';

const theme = createMuiTheme({
  palette: {
    primary: {
      main: '#556cd6',
    },
    secondary: {
      main: '#19857b',
    },
    error: {
      main: red.A400,
    },
    background: {
      default: '#fff',
    },
  },
});

class MyDocument extends Document {

    render() {
        return (
            <html lang="en" dir="ltr">
                <Head>
                    <meta charSet="utf-8" />
                    <meta
                        name="viewport"
                        content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
                    />
                    <meta name="theme-color" content={theme.palette.primary.main} />
                    <link
                        rel="stylesheet"
                        href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap"
                    />
                </Head>
                <body>
                    <Main />
                    <NextScript />
                </body>
            </html>
        );
    }
}

MyDocument.getInitialProps = async ctx => {

    const sheets = new ServerStyleSheets();
    const originalRenderPage = ctx.renderPage;

    ctx.renderPage = () =>
        originalRenderPage({
            enhanceApp: App => props => sheets.collect(<App {...props} />),
        });

    const initialProps = await Document.getInitialProps(ctx);

    return {
        ...initialProps,
        styles: (
            <React.Fragment>
                {sheets.getStyleElement()}
                {flush() || null}
            </React.Fragment>
        ),
    };
};

export default MyDocument;

Check out this Material UI example. There's also an interesting discussion thread 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

What is the best way to display a loading indicator on a Next.js page?

At times in Next.js, there can be a delay in loading a page without any visual cues to show that the page is changing after triggering a <Link /> click or using router.push. Imagine being on a dictionary website looking at a word definition. You the ...

What is the best way to remove the responsive features of a Bootstrap website when the width is less than 786

My current dilemma is with my Bootstrap-based website. I am trying to make it unresponsive for devices with a screen width of less than 768px, but responsive as usual for widths greater than or equal to 768px. This is what I have attempted so far. In my g ...

I keep encountering a 404 error page not found whenever I try to use the useRouter function. What could

Once the form is submitted by the user, I want them to be redirected to a thank you page. However, when the backend logic is executed, it redirects me to a 404 page. I have checked the URL path and everything seems to be correct. The structure of my proje ...

The occurrence of TypeError in next.js Dropzone stating that (0 , _mantine_core__WEBPACK_IMPORTED_MODULE_0__.rem) is not a function is indicating

I am encountering an issue while trying to render a dropzone component using Next.js and Mantine. For reference, I am following the documentation at . Here is the import statement: import dropzone I am receiving an error message that says: I have inclu ...

Vanishing Act: React-js MUI Tooltip vanishes upon clicking

The standard behavior of the MUI Tooltip is as follows:
 If the button/icon to trigger a tooltip is not in focus, the tooltip will not disappear when clicking directly on the popper. However, if the button/icon is focused, the tooltip will disappear upo ...

What is the best way to align an image in the middle of an image slider within a Bootstrap

Struggling to align the image properly in a Bootstrap 5 image slider carousel: https://i.sstatic.net/upPza.png <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel"> <div class=&qu ...

In JavaScript, the function yields a proxy rather than an object

Let's say I have an array: const arr = ['one', 'two', 'three'] Now, imagine I have a function that is designed to take an array of strings and return an array of objects: const func = (arr) => arr.map(item => ({str ...

Encountering numerous challenges while attempting to create a switch theme button with the help of JavaScript's localStorage and CSS variables

It's frustrating that despite all my efforts, I'm still stuck on implementing a small feature for the past 5-6 hours. I need assistance with storing a single variable in the user's localStorage, initially set to 1. When the user clicks a but ...

Challenges with npm and Node.js compatibility in a Vite project

I've run into a problem while attempting to launch my Vite project using npm. After updating Node.js to version 18.16.0, I'm now receiving the following error message: The specified module could not be found. \?\C:\Users\Riaj& ...

``Incorporating best practices: Setting the height of the parent container equal to the height of

When designing a container, is it considered beneficial to assign each child within the container its own height property, even if the parent container has already been allocated a specific height? If not, are there alternate methods available for transfer ...

Disabling an animation in an Android TabLayout when a specific tab is selected

Whenever I touch on TabLayout, a brief flash of grey color appears. How can I disable this effect?https://i.sstatic.net/shUOW.png ...

Utilize the useCallback hook within each individual list item component rather than in the parent component

I recently developed a React app that features a list of items with a delete action. As I understand it, by passing this delete action from the parent (the item container), I could utilize "useCallback" in the parent component to avoid unnecessary recreati ...

What is the process for updating button text upon clicking in Angular?

To toggle the text based on whether this.isDisabled is set to false or true, you can implement a function that changes it when the button is clicked. I attempted to use this.btn.value, but encountered an error. import { Component } from '@angular/core ...

Adding or removing a class on hover in Tailwind: The simple way!

Is there a way to change the class upon hovering an object using tailwind classes? <span className='group inline-block relative'> Hello <span className='hidden absolute -top-16 left-16 group-hover:inline-block'>&#45; ...

Is it possible to update the useContext value within a child component so that all other child components can access the updated value?

Is there a way to set a default value (like null) in a parent context and then change that value in a child component so other children can access the updated value? For example, imagine we have an App.jsx file where a userContext is created and passed do ...

Firefox not supporting position fixed within relative parent

Two columns are displayed here, with the left column showing a list and the right column displaying information based on the selected element from the list. Due to the large size of the list, I implemented a feature where the right column stays fixed at t ...

Opacity of ripple effect in React Material UI transformations

I recently discovered Material UI and I'm really loving it! You can find more information about it here: https://material-ui.com/. One thing I was curious about is how to adjust the opacity of the ripple effect on a normal button. I came across this ...

Bootstrap 4 Card Body Spinner Overlay with Flex Alignment

Seeking to center a spinner both vertically and horizontally within a bootstrap 4 card body. Despite trying my-auto, justify-content-center & align-items-center, it seems like I'm missing something. I've double-checked the display types and ...

Override children component class names with Material UI Tooltip Component

Check out this example In this scenario, there are three visible buttons. The first button lacks a tooltip and changes color based on state and hover. The second button includes a tooltip but encounters issues with the className being overwritten, result ...

Ways to maintain image alignment regardless of the size of the window or device?

Let's set the scene. I'm working with 2 images, a background image for a div and another regular image inside that same div. My question is, how can I ensure that both images are always in the exact position of each other, even when viewed on di ...