Challenges with Media Queries post Integration of MUI Library in React

I have been scratching my head for the last few hours. I needed to utilize a react library to design my dog app for a project. Opting for the MUI library, it has been effective for the grid layout. However, the challenge arises when attempting to implement media queries and breakpoints. Perhaps there is something crucial that I am overlooking.

Despite reading through the breakpoint documentation for MUI, I find myself unable to successfully integrate them. My CSS media queries do not seem to be adjusting the layout as desired, specifically in creating a breakpoint at 780px to transition the layout into a single column.

Any assistance on this matter would be greatly appreciated.

App.js

import './App.css';
import './Dog.js';
import './index.css';
import "./Grid.js";
import NestedGrid from './Grid.js';
import "./Resize.js";


function DogApp() {

  return (
    <div className="dogApp">
      <div className ="fixThis">
        <NestedGrid />
      </div>
    </div>

  );
}

export default DogApp;

FetchAPI.js

import React, { useState, useEffect } from 'react'


const FetchAPI = () => {

    const [show, setShow] = useState({});
    const [data, setData] = useState([]);

    const apiGet = () => {
        const API_KEY = "";
        fetch(`https://api.thedogapi.com/v1/images/search?limit=2&page=10&order=Desc?API_KEY=${API_KEY}`)
            .then((response) => response.json())
            .then((json) => {
                console.log(json);
                setData([...data, ...json]);
            });
    };

    useEffect(() => {           //call data when pagee refreshes/initially loads 
        apiGet();
    }, []);

    return (

        <div>
            {data.map((item, id) => (
                <div class="dog">
                    <img alt="dog photos" class="dogImg" src={item.url}></img>
                    {show[id] === false ? <p>{JSON.stringify(item.breeds)}</p> : null}
                    <button onClick={() => setShow((prev) => ({ ...prev, [id]: false }))}>Learn more about this dog!</button>
                    <button onClick={() => setShow((prev) => ({ ...prev, [id]: true }))}>Hide information</button>

                </div>

            ))}
        </div>

    )
}

export default FetchAPI;

Grid.js

import * as React from 'react';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Grid from '@mui/material/Grid';
import FetchAPI from './FetchAPI';

const Item = styled(Paper)(({ theme }) => ({
    backgroundColor: theme.palette.mode === 'dark' ? '#1A2027' : '#fff',
    ...theme.typography.body2,
    padding: theme.spacing(4),
    textAlign: 'center',
    color: theme.palette.text.secondary,

}));


function FormRow() {
    return (
        <React.Fragment>
            
            <Grid item xs={4}>
                <Item>
                    <FetchAPI />
                </Item>
            </Grid>
            <Grid item xs={4}>
                <Item>
                    <FetchAPI />
                </Item>
            </Grid>
            <Grid item xs={4}>
                <Item>
                    <FetchAPI />\
                    
                </Item>
            </Grid>
            
        </React.Fragment>
    );
}

export default function NestedGrid() {
    return (
        
        <Box sx={{ flexGrow: 1 }}>
            <Grid container spacing={1}>
                <Grid container item spacing={3}>
                    <FormRow />
                </Grid>
                <Grid container item spacing={3}>
                    <FormRow />
                </Grid>
                <Grid container item spacing={3}>
                    <FormRow />
                </Grid>
            </Grid>
        </Box>
    );
}

index.css

* {
  margin : 0;
  padding :0;
  box-sizing: border-box;
}

.idDog{
  font-size: 1.5rem;
  
}

.flexOne{
  display: flex;
  flex-direction: row !important;
  width: 50%;
}

.reSizeImage{
  width: 25%;
  height: 25%;
  padding: 10px;
}

.dogImg{
  width: 650px;
  height: 30vh;
  place-content: center;
  object-fit: cover;
}

.flexTwo{
  text-align: center;
  
}

button{
  font-size: 1.2rem;
  font-weight: bolder;
  padding: 10px;
  border-radius: 20px;
  margin-top: 10px !important;
  margin-bottom: 10px !important;
  height: 2.5vh;
  display: grid;
  place-items: center;
  margin: 0 auto;
  background-color: rgb(223, 217, 217);

}




@media screen and (max-width: 780px){
  .dogApp {
    display: flex !important;
    flex-direction: column !important;
  }

   .fixThis{
    flex-direction: column !important;

   }
}

Answer №1

To address my problem, I decided to utilize a pre-designed template

Grid.js

import * as React from 'react';
import AppBar from '@mui/material/AppBar';
import Button from '@mui/material/Button';
import CameraIcon from '@mui/icons-material/PhotoCamera';
import Card from '@mui/material/Card';
import CardActions from '@mui/material/CardActions';
import CardContent from '@mui/material/CardContent';
import CardMedia from '@mui/material/CardMedia';
import CssBaseline from '@mui/material/CssBaseline';
import Grid from '@mui/material/Grid';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import Link from '@mui/material/Link';
import { createTheme, ThemeProvider } from '@mui/material/styles';

function Copyright() {
  return (
    <Typography variant="body2" color="text.secondary" align="center">
      {'Copyright © '}
      <Link color="inherit" href="https://mui.com/">
        Your Website
      </Link>{' '}
      {new Date().getFullYear()}
      {'.'}
    </Typography>
  );
}

const cards = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const theme = createTheme();

export default function Album() {
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <AppBar position="relative">
        <Toolbar>
          <CameraIcon sx={{ mr: 2 }} />
          <Typography variant="h6" color="inherit" noWrap>
            Album layout
          </Typography>
        </Toolbar>
      </AppBar>
      <main>
        {/* Hero unit */}
        <Box
          sx={{
            bgcolor: 'background.paper',
            pt: 8,
            pb: 6,
          }}
        >
          <Container maxWidth="sm">
            <Typography
              component="h1"
              variant="h2"
              align="center"
              color="text.primary"
              gutterBottom
            >
              Album layout
            </Typography>
            <Typography variant="h5" align="center" color="text.secondary" paragraph>
              Something short and leading about the collection below—its contents,
              the creator, etc. Make it short and sweet, but not too short so folks
              don&apos;t simply skip over it entirely.
            </Typography>
            <Stack
              sx={{ pt: 4 }}
              direction="row"
              spacing={2}
              justifyContent="center"
            >
              <Button variant="contained">Main call to action</Button>
              <Button variant="outlined">Secondary action</Button>
            </Stack>
          </Container>
        </Box>
        <Container sx={{ py: 8 }} maxWidth="md">
          {/* End hero unit */}
          <Grid container spacing={4}>
            {cards.map((card) => (
              <Grid item key={card} xs={12} sm={6} md={4}>
                <Card
                  sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}
                >
                  <CardMedia
                    component="img"
                    sx={{
                      // 16:9
                      pt: '56.25%',
                    }}
                    image="https://source.unsplash.com/random"
                    alt="random"
                  />
                  <CardContent sx={{ flexGrow: 1 }}>
                    <Typography gutterBottom variant="h5" component="h2">
                      Heading
                    </Typography>
                    <Typography>
                      This is a media card. You can use this section to describe the
                      content.
                    </Typography>
                  </CardContent>
                  <CardActions>
                    <Button size="small">View</Button>
                    <Button size="small">Edit</Button>
                  </CardActions>
                </Card>
              </Grid>
            ))}
          </Grid>
        </Container>
      </main>
      {/* Footer */}
      <Box sx={{ bgcolor: 'background.paper', p: 6 }} component="footer">
        <Typography variant="h6" align="center" gutterBottom>
          Footer
        </Typography>
        <Typography
          variant="subtitle1"
          align="center"
          color="text.secondary"
          component="p"
        >
          Something here to give the footer a purpose!
        </Typography>
        <Copyright />
      </Box>
      {/* End footer */}
    </ThemeProvider>
  );
}

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

jQuery fade in problem or alternate solutions

When I send a post request to a file and input the response into id='balance', I would like it to have a flickering effect or fadeIn animation to alert the user that it is being updated in real time. I attempted to use the fadeIn() method but it ...

The resolveMX function in Google Cloud Functions is encountering issues when trying to process a list of domains

Here is the task at hand. I have a large list of domains, over 100,000 in total, and I need to iterate through them using a foreach loop to resolve MX records for each domain. Once resolved, I then save the MX records into another database. Below is the c ...

What causes the height and width properties in a div to remain unchanged even after using the zoom/scale CSS?

I'm trying to center a CSS spinner on the page, but I am struggling with making it happen. Even when scaled down by 50%, the height and width remain at 200px. <div class="center" style=""> <div class="uil-default-css" style="width: 200px ...

Guide on loading xml information from a web browser using JavaScript

I have been working on loading data from the browser using a URL and currently utilizing JavaScript to achieve this. window.onload = function() { // This is the specific URL I am attempting to load data from. // The XML fi ...

Filtering the inner ng-repeat based on the variable of the outer ng-repeat

I have a collection of elements. Some of these elements are considered "children" of other elements known as "parent" elements. Instead of rearranging the JSON data received from the server, I am attempting to filter the results within the ng-repeat loop. ...

Challenges with the jScroll Plugin

Trying to implement jScroll to load a partial view multiple times using an increasing page number. The partial view returns a few divs. To achieve infinite scrolling, the partial view needs to have a hyperlink tag that directs to the next page to load. Th ...

Could it be possible that my consecutive POST and GET axios requests are gradually slowing down?

After chaining the POST and GET calls in my code, I noticed a slight slowdown and was curious if this is normal or if there's a more efficient approach. The delay in displaying the google map marker made me think that pushing the newly created marker ...

An introduction to integrating Paged.js with Vue.js3

index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> < ...

Download multiple Highcharts graphs on a single page

When using Highchart Export, I am currently able to download multiple graphs in a single page PDF. However, I would like the first graph to be on the first page and the second graph on the second page when saving as a PDF. You can find the code in the fol ...

Customizing object joining rules in JavaScript arrays

My array consists of different colored items with their respective types and amounts [ { color: 'blue', type: '+', amount: '1' }, { color: 'blue', type: '-', amount: '1' }, { color: 'blu ...

guide on incorporating Google Maps in a Vue.js application

Can anyone help me with displaying a Google Map using Vue.js? I have provided the code below, but I keep getting an error saying "maps is undefined" even though I have installed all the necessary dependencies for Google Maps. <div id="map"></div& ...

Leaving the "OK" button untouched in the sweet alert dialog

While implementing sweet alert in my project, I encountered an issue where the button text was not changing and the cancel button was missing on some pages. On certain pages, it only displayed OK. You can see a screenshot below for reference. https://i.s ...

Eliminate the selected item at random

I'm looking for a way to remove the randomly picked item from my namepicker so that it doesn't appear twice. const Names = [ { name: 'Name1', id: 1 }, { name: 'Name2', id: 2 }, ] btnClick = () => { let ...

What is the best way to use jQuery to attach functions to every input element?

Imagine you have a set of HTML markup and CSS like this: #CSS .inputhelp_text { background: #000; color: #fff; } .nodisplay { display: none; } <input class="inputhelp" id="firstname" /><span class="inputhelp_text nodisplay" id="help_firstname"& ...

Button group malfunctions on smaller screens

After integrating a button group into my new website, I noticed that the first two buttons stop functioning properly on smaller screens. Surprisingly, if I remove the text-center div, all buttons cease to work entirely. Despite attempting various solution ...

The issue of execution order in JavaScript Recursion with promises

In the process of developing a method for creating markup to be used in a web app's off-canvas navigation. One of the challenges I am facing is making an asynchronous callback to another service that provides children nodes for the parent menu node (r ...

Issue with Fullcalendar's events.php causing JSON object retrieval failure

I'm attempting to send a JSON object as a response to my fullcalendar ajax request, but instead of returning the desired result, it only returns an array. Although I am relatively new to JSON and PHP, I have conducted extensive research and have yet t ...

The hovering over a table data element results in a superior transformation

I recently created a table with an interesting structure where the first <tr> contains two <td> elements (the first one having a rowspan), while the second <tr> only has one <td>. My goal is to have hovering over the <td> in t ...

Am I utilizing the htmlspecialchars function properly?

My main objective is to protect the user from malicious code and prevent XSS attacks. I have implemented a series of checks to filter the user's input before storing it in the database. The user input is stored in the $post variable. $post = htmlspec ...

Exploiting the Power of useRef with TypeScript in Functional Components of React

I'm having trouble accessing the child component method from the parent component using useRef. Eventually, the SayHi method will be responsible for updating the hook state in the child component. Unfortunately, I am encountering some bugs that I can ...