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

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

I am working on an HTML form that is designed vertically, but I am unsure of how to arrange two text fields side by side on the same line

I'm struggling with formatting my HTML form to have two text fields on the same line instead of stacked vertically. In the example below, I want the Size, Width, and Height fields to be aligned horizontally rather than one below the other. <form c ...

Is it possible to utilize Webpack 5's ChunkGroup API with several entries?

I am encountering an error message when attempting to upgrade from Webpack 4 to Webpack 5. The error states: Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API) I have searched for information o ...

Dynamic Formatting with Vue JS: Enhancing Phone Number Input

I am working on a form that includes a phone number input field, and I want the formatting of the number to change to a standard telephone number format as the user types. Can someone provide guidance on how this can be achieved using JavaScript and Vue 3? ...

Ways to integrate PHP MySQL with NodeJS and SocketIO

Currently, I am working on developing a chat application. I have successfully implemented features like creating accounts, logging in, selecting, viewing, and more using PHP MySQL. Now, I am venturing into the Instant Messaging aspect by utilizing NodeJS a ...

Using useState as props in typescript

Let's imagine a situation where I have a main component with two smaller components: const MainComponent = () => { const [myValue, setMyValue] = useState(false) return ( <> <ChildComponent1 value={myValue} setValue={set ...

Tips for maintaining previously accessed data when utilizing useQuery

I am currently working on incorporating a GET request using useQuery from the react-query library. Below is the relevant code snippet: import queryString from "query-string"; import { useRouter } from "next/router"; const { query } = ...

Combining Cognito and Lambda: How to Match User Login Data with a PUT Parameter?

Presented here is my current application setup: - Sensors sending data to Amazon RDS (MySQL) - User Interface built with React.js, connected to Lambda for accessing data in Amazon RDS ! All user authentication is handled through Cognito. Ther ...

Why can't we use percentages to change the max-height property in JavaScript?

I am currently working on creating a responsive menu featuring a hamburger icon. My goal is to have the menu list slide in and out without using jQuery, but instead relying purely on JavaScript. HTML : <div id="animation"> </div> <button ...

Transform a REACT js Component into an HTML document

I'm working with a static React component that displays information from a database. My goal is to implement a function that enables users to download the React component as an HTML file when they click on a button. In essence, I want to give users ...

What is the best way to continuously execute the 'onclick' function using AJAX inside a specific ID?

My challenge involves implementing a new AJAX upload feature to insert a data element from the onClick event in multiple rows. The issue I am facing is that it works fine for the first row, but when I add subsequent rows, the function no longer works upon ...

Retrieving a single item from an array of objects with the help of body parser

I need assistance with sending an array of objects to a post route in my express app. Here is my form (written in ejs format): <form action="/archiveList/<%= list._id %>" method="POST"> <input type="hidden" name="list" value = <%= items ...

How come characteristics of one particular div element are transferring to unrelated div elements?

Recently, I created a small practice website and encountered an issue that is quite frustrating. Here's the div structure I used: <div class="work-process"> <div class="container" align="center"> <div class="col- ...

The NPM Install process seems to be skipping certain files that were successfully installed in the past

When I first installed NPM Install in a folder, it created multiple folders and files: node_modules public src .DS_Store package.json package-lock.json webpack.config.js After that, npm start functioned perfectly. Now, as I embark on a new project for th ...

Error in Express Post Request: Headers cannot be modified after being sent to the client

I am a beginner in Node.js and I am facing some challenges while working on an app for learning purposes. I encountered the following issue: Error: Can't render headers after they are sent to the client. I am unsure of how to resolve it. C:\Us ...

Creating a two-column post loop in Wordpress is a great way to display content in a

I've been attempting to separate posts for a long time without success. No matter what variations I try, the result is always either a single post or duplicating all of them. In other words, multiple posts are not displaying as intended. If anyone ha ...

The module cannot be located due to an error: Package path ./dist/style.css is not being exported from the package

I am facing an issue with importing CSS from a public library built with Vite. When I try to import the CSS using: import 'rd-component/dist/style.css'; I encounter an error during the project build process: ERROR in ./src/page/photo/gen/GenPhot ...

Displaying a collection of items using Rails, implementing form_for and integrating Ajax functionality

Looking to display a list of "Interests" for users to "follow" by clicking on a button linked to the Interest's image. Once the follow button is clicked, the Interest and its image should be removed from the list. Attempting to use a hide function in ...

How can you ensure an element's height matches its width within an Ionic framework?

I am currently creating an application using the Ionic framework, and I am looking to set a square image as the background. The challenge is to ensure that the image scales appropriately for different screen resolutions; ideally, it should occupy the full ...

Experiencing a blank page error when trying to render a partial view using Angular.js

Can someone assist me? I am encountering an issue where the partial view is not rendering properly using ui-router in Angular.js. Below is my code snippet. <!DOCTYPE html> <html lang="en" ng-app="Spesh"> <head> <meta charset="utf- ...