Enhance your Material UI Button with Advanced Text Alignment Options for Compact Screens

As a beginner in React and Material-UI, I'm attempting to customize a set of buttons within my app bar with background images for a cleaner look. Drawing inspiration from various online examples, I've managed to style them to my liking on larger screens (md++). However, upon resizing to a smaller breakpoint, the button images start stacking vertically (which is desired) but the accompanying text shifts to the left. Despite my efforts to adjust the alignment to the right, it doesn't seem to be the correct approach. Is there a specific way to make the text flexible so that it stays centered?

import React from 'react'

import { AppBar, Toolbar } from "@mui/material";
import { makeStyles } from '@mui/styles'
import Button from '@mui/material/Button'
import Stack from '@mui/material/Stack'
import ButtonBase from '@mui/material/ButtonBase';
import { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';

const useStyles = makeStyles(theme => ({

    button: {
        ...theme.typography.mainmenu,
        borderRadius: "40px",
        marginLeft: "1px",
        height: "45px",
        "&:hover": {
            backgroundColor: theme.palette.secondary
        }
    },

}))

const images = [
    // Image data omitted for brevity
];
const Image = styled('span')(({ theme }) => ({
    // Styles for image span
}));

const ImageButton = styled(ButtonBase)(({ theme }) => ({
    // Styles for image button
}));

const ImageSrc = styled('span')({
    // Styles for image source
});
const ImageBackdrop = styled('span')(({ theme }) => ({
    // Styles for image backdrop
}));

const ImageMarked = styled('span')(({ theme }) => ({
    // Styles for image marked
}));

const Header = () => {
    const classes = useStyles();
    return (<React.Fragment><AppBar position="sticky" className={classes.appBar}>
        <Toolbar disableGutters className={classes.mainToolbar} sx={{ justifyContent: "center" }}>
            <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={10}>
                {/*  Buttons content */}
                <Box sx={{ display: 'flex', flexWrap: 'wrap', minWidth: 900, width: '100%' }}>
                    {images.map((image) => (
                        <ImageButton
                            focusRipple
                            key={image.title}
                            style={{
                                width: image.width,
                            }}
                        >
                            <ImageSrc style={{
                                backgroundImage: `url(${image.url})`
                            }} />
                            <ImageBackdrop className="MuiImageBackdrop-root" />
                            <Image>
                                <Typography
                                    component="span"
                                    variant="subtitle1"
                                    color="white"
                                    fontWeight="bold"

                                    sx={{
                                        position: 'relative',
                                        p: "7em",
                                        pt: "2em",
                                        pb: (theme) => `calc(${theme.spacing(1)} + 6px)`,
                                    }}
                                >
                                    {image.title}
                                    <ImageMarked className="MuiImageMarked-root" />
                                </Typography>
                            </Image>
                        </ImageButton>
                    ))}
                </Box>
            </Stack>
        </Toolbar>
    </AppBar>

    </React.Fragment >
    )
}

export default Header

Answer №1

Although I have moved past this stage, for those who stumble upon it, I successfully revamped my application using MUI with the following approach:

import useMediaQuery from '@mui/material/useMediaQuery'

along with examples like:

const matches = useMediaQuery(theme.breakpoints.down("md"))

to dynamically adjust the styles of the application based on screen size

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

Date selection feature in Material UI causing application malfunction when using defaultValue attribute with Typescript

Recently, I discovered the amazing functionality of the Material UI library and decided to try out their date pickers. Everything seemed fine at first, but now I'm facing an issue that has left me puzzled. Below is a snippet of my code (which closely ...

Why isn't my Next.js middleware working properly with TypeScript?

My issue arises from the fact that, despite following the documentation, the middleware in Next.js is not functioning as I anticipated. I experimented with what I thought was the simplest middleware possible. I expected that when navigating to /, a conso ...

Choose specific items and move them to a different page

I'm currently working on developing an app and I've hit a roadblock when it comes to allowing users to select multiple images to be passed to another screen. Can anyone offer some guidance on how to accomplish this? Your help would be greatly app ...

Material 15 provides a sleek and modern button design featuring both an icon and text

Here's a simple question - how can I create a button with both icon and text in material 15? <button mat-button> <mat-icon>keyboard_arrow_left</mat-icon> Back To Home </button> https://i.stack.imgur.com/Llhx1.png However, ...

The hook call you made in next.js/react is invalid and cannot be

I recently followed a tutorial on creating a hamburger menu in react/next.js. You can check out the tutorial here. import { useState } from "react"; import user from '../styles/userview.module.css' export function PageHeader() { con ...

Eliminating the boundaries of Bootstrap accordion

I'm currently working on creating Bootstrap accordion menus and I'm attempting to remove the border that appears when it's collapsed and expanded. Below is the code I've been working on: <div class="accordion"> <div ...

exploring div element(s) with jQuery

My HTML page contains multiple div elements in the body. I have also included buttons with associated click functions in jQuery to change the background-color of a div element based on the button pressed. However, I'm facing an issue at the 'term ...

Navigating with React Native post Successful Login

Can anyone assist me with a problem I'm facing? I'm struggling to figure out how to redirect to the home page after login. It seems like I need to refresh the app to achieve this. In my app.js file, there is a const named isSigned that retrieves ...

Site with Three Steady Columns

While I know that this question has been asked in the past, I'm eager to see if there have been any recent changes. I am currently searching for a fixed 3 column layout using html/css, with the main content (middle) area being located first in the DO ...

Do not forget to implement Array.find when working with the useSWR hook in Next.js

I have the following code: const fetcher = (url: string) => axios.get(url).then((r) => r.data); const {data} = useSWR("api/data", fetcher, {refreshInterval: 10000}) console.log(data.find(d => d.id === "123")) The API path is ...

Is there a correct way to accomplish this task? How could I go about achieving it?

Currently, I am delving into the world of react. While following along with some video tutorials, I encountered a roadblock in the request.js file. The issue popped up during the build process ./src/Row.js Line 16:45: 'fetchUrl' is not define ...

Problem encountered in a simple Jest unit test - Unexpected identifier: _Object$defineProperty from babel-runtime

Struggling with a basic initial test in enzyme and Jest during unit testing. The "renders without crashing" test is failing, as depicted here: https://i.stack.imgur.com/5LvSG.png Tried various solutions like: "exclude": "/node_modules/" in tsconfig "t ...

Changes in an image element's transition can result in either resizing or shifting positions

When I apply an opacity transition to an img element as shown here, I notice that the size of the image changes or it appears to move at the start and end of the transition. Below is a simple CSS code for styling: img{ height:165px; width:165px; ...

The Div element containing the rollover button/picture is failing to resize properly as the window is decreased in size

Whenever I try to resize my browser window in Firefox or Chrome, the div ends up moving instead of resizing. I've searched on stackoverflow for answers but haven't found any solutions yet. Can someone please help me with this issue? Here is what ...

What is the best way to transfer a UserID from State to a GET URL?

I have my userInfo saved in a state variable const [users, setUsers] = useState([]) I need help passing the userId into the axios URL to fetch posts of a specific user. Here's what I have tried. I know it's not correct, so please assist me. Das ...

Is it possible to attach the payload to the beginning of a slice in the extraReducer using React Toolkit?

Using createSlice, I have created a slice and want to add the payload to the root of this slice. If we consider this slice as "payments" and the initial state is an empty object ({}), my goal is to store all payments inside this object in arrays. const ini ...

State of cart is currently empty, local storage fails to reflect product quantity changes, utilizing redux as a potential solution

I am experiencing an issue with my state where the cart appears empty. When I add a new product, the state's cartItem[] is empty and does not display previous items. Similarly, state.cartItems is also an empty array when retrieved from useSelector(). ...

Difficulty encountered when trying to customize a polymer element that has been expanded (paper-slider)

I've been customizing the Polymer paper-slider element to handle an enumerated list and cycle through these values in the slider instead of just showing numeric values. However, I'm struggling with getting the styles to align properly. When you r ...

Tips for preventing unnecessary re-renders when adding an item to a list

I'm facing an issue with my functional component that requires updating. export const VendorCategory = ({setShowProgress, user}) => { const classes = useStyles() const theme = useTheme() const listElements = [] const [dummyCategory, ...

React: The issue with async and await not functioning as expected when using fetch

I am working with an API on a Node server that returns JSON data like this: {"result":[{"ProductID":1,"ProductName":"iPhone10","ProductDescription":"Latest smartphone from Apple","ProductQuan ...