Tips for creating a mobile-responsive React + MUI component

A React component utilizing Material-UI (MUI) has been created and I am working on making it mobile responsive. The current appearance is as follows:

https://i.stack.imgur.com/8z0T8.png

My goal is to have it look like this:

https://i.stack.imgur.com/L8gjo.png

The relevant code for the component is shown below:

import React from 'react';
import {
  Box, Typography, Paper, Rating, Avatar,
} from '@mui/material';


type CarInfoProps = {
  title: string;
  imageUrl: string;
  rating: number;
  comments: string[];
};

const CarInfo: React.FC<CarInfoProps> = ({
  title, imageUrl, rating, comments,
}) => {
  return (
    <Box
      display="flex"
      flexDirection="column"
      alignItems="center"
      justifyContent="center"
      height="100vh"
    >
      <Paper elevation={3}
        style={{
          padding: '16px', display: 'flex', flexDirection: 'column', alignItems: 'center', height: '980px', width: '955px',
        }}>
        <Typography variant="h5" gutterBottom style={{ textAlign: 'center' }}>
          {title}
        </Typography>
        <Avatar alt={title} src={imageUrl} style={{ marginTop: '16px' }} />
        <Box style={{ marginTop: '16px' }}>
          <Typography variant="body1">Car Info:</Typography>
          {/* Add additional car information here */}
        </Box>
        <Box style={{ marginTop: '16px' }}>
          <Typography variant="body1">Rating:</Typography>
          <Rating value={rating} readOnly />
        </Box>
        <Box style={{ marginTop: '16px' }}>
        </Box>
      </Paper>
    </Box>
  );
};

export default CarInfo;

Despite trying various methods, achieving the desired mobile responsiveness remains a challenge. Seeking assistance on structuring the styles or any MUI-specific considerations needed to meet the desired mobile layout.

I inquired about the same issue yesterday but was unable to find a solution.

Answer №1

One important tip is to steer clear of using inline CSS whenever possible! After reviewing MUI, it seems like you need to specify its attributes using xs or md to determine how much space an element should occupy on different screen sizes. Here's an example:

const MyComponent = () => {
  return (
    <Grid container spacing={2}>
      <Grid item xs={12} md={6}>
        <Paper>Content 1</Paper>
      </Grid>
      <Grid item xs={12} md={6}>
        <Paper>Content 2</Paper>
      </Grid>
    </Grid>
  );
};

In this scenario, the xs={12} indicates that the component will span the full width on small screens (xs), while md={6} specifies that on medium screens and larger (md), the component will take up half of the available width.

Although Material-UI offers tools for responsiveness, developers must still craft a responsive design strategy tailored to their application's unique requirements.

Hopefully, this information proves helpful or provides some valuable insights!

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 significance of the "rc" within the version structure of an npm package?

Can someone help me understand what the rc in 2.2.0-rc.0 signifies? I'm curious if it indicates that this version is ready for production use. ...

A perfectly organized and justified menu with evenly spaced horizontal list items

I couldn't find a solution to evenly spacing out a series of list items for a menu styled list. After realizing CSS alone wasn't enough, I decided to incorporate some javascript (jQuery). My goal was to have equal padding between each LI without ...

Collapse dropdown menus upon clicking outside of them

As a newcomer to coding, I'm trying to figure out how to create multiple dropdown menus where each one collapses when you click outside of it. I've been struggling with the code I wrote for weeks now - I want to have 3 dropdown menus but only one ...

Is a backend necessary for my ReactJS web application?

Hey there! I am currently in the process of creating a front-end web application using ReactJS. My app will display various arrays of dogs, cats, and other animals, each with multiple properties and a couple of images. The user interface features a search ...

Clicking outside of a focused div does not trigger a jQuery function

Check out this HTML snippet: $html .= " <td><div class='edit_course' data-id='{$id}' data-type='_title' contenteditable='true'>{$obj->title}</div></td>"; Next, see the jQuery code below: ...

How are the script name and script file connected in WordPress enqueuing?

When adding a jQuery script to the function.php file using the enqueue method, how does the script name relate to the actual file that contains the jQuery code? Is the script name arbitrary, or is it derived from either the file name or the actual script w ...

Triggering the AJAX function in the main window

My HTML webpage has a hyperlink that, when clicked, opens the same page in another window with a hash value appended to the URL using window.open. For example, the URL could look like this: http://mywebsite.com#hash=value The webpage contains a JavaScript ...

An unexpected error occurred: ReferenceError - document is undefined

Error Alert: Unhandled Runtime Error ReferenceError: doc is not defined Source of Issue components\Modal.js (42:18) @ updateDoc 40 | await uploadString(imageRef, selectedFile, "data_url").then(async (snapshot) => { 41 | const do ...

Steps to ensure that a particular tab is opened when the button is clicked from a different page

When I have 3 tabs on the register.html page, and try to click a button from index.html, I want the respective tab to be displayed. Register.html <ul class="nav nav-tabs nav-justified" id="myTab" role="tablist"> <l ...

Testing a Jest unit on a function that invokes another function which in turn returns a Promise

I have a function that triggers another function which returns a Promise. Below is the code snippet for reference: export const func1 = ({ contentRef, onShareFile, t, trackOnShareFile, }) => e => { trackOnShareFile() try { func2(conte ...

Changing a password on Firebase using Angular 5

I am in the process of developing a settings feature for user accounts on an application I've been working on. One key functionality I want to include is the ability for users to update their password directly from the account settings page. To enable ...

Is it possible to send emails from a local server to Gmail, Yahoo, or Rediff?

Currently, I am developing a feature that allows users to send emails to any recipient including Yahoo and Gmail. Below is the code snippet for my contact form: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 ...

How to prevent links from being affected by the Gooey effect in D3

Issue: When applying the Gooey effect, the links are also affected, resulting in a teardrop shape instead of a circle. The code snippet includes a dragged() function that allows users to detach node 1 from node 0 and reconnect them by dragging. The code s ...

Having issues with my JavaScript code - it just won't function

I am having an issue with my JavaScript code. I don't receive any errors, but when I click the submit button, nothing happens. I have followed a video tutorial and watched it twice, but I can't seem to figure out what is wrong here. Here is the ...

What could be causing the Socket.io client to fail connecting to a Next.js custom server?

This is my first experience working with websockets. I have developed a custom Next.js server, here is the code: const { Server } = require("socket.io"); const express = require("express"); const { createServer } = require("http&qu ...

The self-made <Tab/> element is not functioning properly with the ".Mui-selected" class

I have customized a <Tab/> element and I want to change its selected color using Sandbox demo code export const Tab = styled(MuiTab)({ "&.Mui-selected": { color: "red" } }); However, I've noticed that: 1. Apply ...

React does not always remove event listeners when using the useEffect hook's return callback

I have a functionality in my component where it initializes a key event listener. This event is supposed to trigger an API call to fetch random data. useEffect(() => { const keyUpEvent = (event) => { if (event.code === "Enter") { ...

Sending data from TextBox as json format

JavaScript Code: var latitude = document.getElementById("<%=txt_Lat.ClientID %>").value; var longitude = document.getElementById("<%=txt_Long.ClientID %>").value; var jsonData = {latitude: latitude, longitude: longitude}; var jsonString = JSO ...

None of the angular directives are functioning properly in this code. The function attached to the submit button is not executing as expected

I've experimented with various Angular directives in this code, but none seem to be functioning properly. I'm wondering if a library file is missing or if there's some issue within the code itself, potentially related to the jQuery file. The ...

Tips for fixing an error encountered when running a react native project for the first time

I am encountering some errors while attempting to run this project for the first time and I am unable to resolve them. Below is the content of the package.json file: { "scripts": { "start": "expo start", "andro ...