Is there a way to use flexbox in a grid to center only a specific tab from MUI?

I am working with an array of tabs and encountering a layout issue. The tabs need to share the available space when there's more than one tab, but when there's only one tab, it should be positioned in the middle of the column. How can I address this problem while using flex? Here is my current code:

import type { ReactElement } from 'react';
import { useState } from 'react';

import { Box, Tab, Typography, useMediaQuery, useTheme } from '@mui/material';
import Tabs, { tabsClasses } from '@mui/material/Tabs';

const MOCK_TAB_VALUES = [
    { month: 'August 2023', date: '20.08.2023' },
    // Additional tab objects commented out for brevity
];

export const FormTabComponent = (): ReactElement => {
    const [value, setValue] = useState <number>(0);
    const theme = useTheme();
    const isLargeScreen = useMediaQuery(theme.breakpoints.up('lg'));

    const handleTabChange = (event, newValue) => {
        setValue(newValue);
    };
    const isDarkMode = theme.palette.mode === 'dark';
    return (
      <Tabs
        sx={{ 
            // Styling properties here
        }}
        value={value}
        variant="scrollable"
        onChange={handleTabChange}
      >
        {MOCK_TAB_VALUES.map((tab, index) => (
          <Tab
            key={index}
            sx={{ flex:1 }}
            label={(
              <Box
                sx={{
                    display: 'flex',
                    flexDirection: 'column',
                }}
              >
                <Typography
                  variant={isLargeScreen ? 'headings.h4' : 'buttons.small'}
                  color="inherit"
                >
                  {`${tab.month.slice(0, 3)} ${tab.month.slice(-4)`}
                </Typography>
                <Typography variant="captions.default" color="inherit">
                  {tab.date}
                </Typography>
              </Box>
            )}
          />
      ))}
      </Tabs>
  );
};

The screenshot shows that the single tab is not centered within the grid. https://i.sstatic.net/oYMGX.png

You can view the codesandbox example for further details: https://codesandbox.io/s/zealous-johnson-n5rqpd?file=/FormTabComponent.tsx

Answer №1

Could you kindly review the solution provided below? Hopefully, it meets your needs.

In order to center the Tab, you must include styling in <Tab sx={{ flex: 1 }} > by adding margin like so:

<Tab sx={{ flex: 1, margin: "0px auto" }} >

You can also view it on this website: https://codesandbox.io/s/focused-bird-sh6w25

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

Encountering a TypeError stating that searchField.toLowerCase is not a function while employing hooks and redux in the

I've been working on a project to dive deeper into react. Recently, I made the switch to using hooks and attempted to integrate redux into it. However, I encountered an error that says: TypeError: searchField.toLowerCase is not a function After consu ...

Content within the Grouped Bar Graph Bar D3.js

I referred to https://bl.ocks.org/mbostock/3887051 and customized the bar chart by adding text inside each bar representing a count, such as Upstream is 50, so the number 50 should appear in the bar itself. Despite trying solutions from resources like D3. ...

Getting started with express-react-views in Sails.js: A beginner's guide

After trying to integrate express-react-views into Sailsjs, setting engine: 'jsx' in config/views.js, I encountered the following error: info: Starting app... warn: [Function] error: Invalid view engine (jsx)-- are you sure it supports `consoli ...

I'm looking to divide the background horizontally into two sections, with one side being a solid black color and the other side incorporating a gradient of two colors, such as purple transitioning into pink

body { height:100%; background: linear-gradient(top, #d808a4 50%, black 50%); background: linear-gradient(top, #d808a4 50%,black 50%); background: linear-gradient(to bottom, #d808a4 50%,black 50%); height: 229vh; } I am trying to creat ...

Organizing a Vue.js SPA project: Implementing Vuex store and API calls efficiently

Here is how I have organized the structure of my Vue app: components/ article/ AppList.vue common/ AppObserver.vue NoSSR.vue layout/ AppFooter.vue AppHeader.vue ui/ AppButton. ...

Combining Json, Jquery Autocomplete, and PHP to customize the displayed search options based on multiple items within the Json data

I have a PHP file that returns an array of results, with the 'Name' field being one of them. I want to customize my jQuery autocomplete feature to only search by the 'Name' field and suggest results based on that. However, once a sugges ...

Decrease the size of the hyperlink area to only the center portion of the text for a more precise click target

Normal text links are present: <a href="projects.html">Projects</a> Is it feasible to make only the middle part of the letters clickable? Such as excluding the top of 'P' or the bottom of 'j'? a { font-size: 50px; ...

We regret to inform you that the request cannot be processed by our Express

Currently, I am in the process of learning nodejs and expressjs and attempting to integrate it into the Spring MVC pattern. My intention behind this is to maintain cohesion within my files. However, the results are not quite aligning with my expectations.. ...

Material-UI web application experiencing crashes due to worn-out cards, resulting in element type being declared as invalid and raising an error

After reviewing numerous similar SO questions, it appears that the issue always comes down to problems with imports. Typically, these involve mistyped import destinations or missing braces, but I have double-checked and found no such issues in my code. ht ...

Generating a PDF file from HTML div content using a button click

I am looking to export a specific div section as a PDF file. The div contains a mix of text, images, and charts. <div id="newdiv"> <img src="http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/ ...

Having trouble configuring the sticky-footer correctly

Currently enrolled in a web development course on Udemy, I am facing an issue with the footer on my webpage. Even after setting its CSS position to relative, the footer overlaps the content when more data is added. However, removing this positioning causes ...

What benefits does utilizing unordered lists provide in navigation bars?

Throughout my research, I have come across numerous tutorials detailing the process of creating a navigation bar. They often begin by adding an unordered list and then proceed to remove the default styling such as bullet points and margins from both the ...

Ensuring the same height for the navigation bar and logo with aligned vertical text

I'm in the process of recreating a simple navigation menu and I've reached the section where I am encountering an issue with the list items. The orange li element is not filling up 100% of the width, and I also need the links to align in the midd ...

Changing the background color of a page to match the background color of a button in React, which can be updated at any time

I have a special button called ArbitraryBtn that, when clicked, changes the page's background color to random colors: import React from 'react'; export const changeToArbitraryColor = () => (document.body.style.backgroundColor = ...

Once the grunt build process is complete, execute "heroku run fileName" to launch the

In order to gain a deeper understanding of Heroku scheduling, I decided to delve into an informative post on the topic and followed the instructions provided to build the app. The highlight of the post was when I successfully executed heroku run numCheck a ...

Is there a way to display the React application with redux utilizing ReactJS.NET?

After creating a Single Page Application using React, Redux, and React-Router, I am looking to enhance its performance by rendering it with ReactJS.NET. Using Webpack, the SPA is compiled into one Bundle.js file. Now, I want to embed this bundle into an A ...

What are some ways in which I can utilize the Ember Handlebars helper?

Similar Question: Using logical operators in a Handlebars.js {{#if}} statement Below is the code snippet provided: {{#each dataArray}} <li>{{#isTrue idVal1 idVal2}} display some text1 {{else}} display some text2 {{/isTrue}} & ...

Using CSS to enforce a specific height for text by overflowing its parent container horizontally

I have a lengthy phrase that takes up too much space on mobile devices. Here is an example: .artificial-phone-viewport { width: 320px; height: 500px; border: 1px solid darkgrey; } .container { width: 100%; height: 100%; } .text { /* * Do ...

Navigating through props outside a class component in React

I'm struggling to grasp how I can access props that are defined outside of a React class component. In the code snippet below, all props are clearly outlined except for this.props.checkboxArray, which is currently throwing an error "cannot read prope ...

The issue of children inside a parent div not respecting the height value set to 100% when the parent div has a min

My goal is to adjust the height of children elements within a parent div that has a min-height of 100%. I want the wrapper's height to dynamically adjust based on the content it contains. When I set the min-height to 100%, the wrapper expands accordin ...