Drop-down and autocomplete feature in Material UI design framework

Encountering an issue with aligning a label with a dropdown in material UI, and for some reason, this behavior is observed: https://i.sstatic.net/n7pj8.png

Struggling to get them aligned on the same row.

This is the code snippet of my component:

const useStyles = makeStyles(theme => ({
    root: {
        justifyContent: 'center',
        display: 'flex',
    },
    formControl: {
        margin: theme.spacing(1),
        minWidth: 120,
      },
    selectEmpty: {
    marginTop: theme.spacing(2),
    },
}));

function DutPreferencesTab(props) {
    const classes = useStyles()
    const {data} = props
    console.log(data)
    const [age, setAge] = React.useState('');

    const handleChange = (event) => {
      setAge(event.target.value);
    };
    return (
        <div style={{display: 'flex', direction: 'row'}}>
             <CustomLabel  text={'Relay:'}  variant={"subtitle1"} />
                     <FormControl className={classes.formControl}>
                         <InputLabel id="demo-simple-select-label">Age</InputLabel>
                         <Select
                         labelId="demo-simple-select-label"
                         id="demo-simple-select"
                         value={age}
                         onChange={handleChange}
                         >
                         <MenuItem value={10}>Ten</MenuItem>
                         <MenuItem value={20}>Twenty</MenuItem>
                         <MenuItem value={30}>Thirty</MenuItem>
                         </Select>
                     </FormControl>
        </div>
    )
}

CustomLabel.js

import React from 'react'
import Typography from '@material-ui/core/Typography';
import clsx from 'clsx';

function CustomLabel({text, variant, styles}) {
    return (
        <div className={clsx(styles)}>
            <Typography variant={variant} gutterBottom>
                {text}
            </Typography>
        </div>
    )
}

export default CustomLabel

Tried various solutions but unable to align them on the same row. The issue seems to be specific to dropdowns as other texts are aligned perfectly with the label. Any insights on what could be missing?

Appreciate any help!

Answer №1

By inspecting the elements in dev tools, you'll notice they are aligned correctly. The issue arises from the Select component being taller than the associated label, causing them to align at the top due to default settings.

https://i.sstatic.net/WoIaR.png

When an item is selected and the label in the Select (e.g., "Age") moves up, the reason for its height becomes clearer.

https://i.sstatic.net/jLbz7.png

To resolve this, adjust the CSS property align-items on the wrapping div containing the label and select. Setting it to baseline appears to be the optimal choice here.

https://i.sstatic.net/QU0LH.png

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import CustomLabel from "./CustomLabel";

const useStyles = makeStyles((theme) => ({
  root: {
    alignItems: "baseline",
    display: "flex"
  },
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  }
}));

export default function DutPreferencesTab(props) {
  const classes = useStyles();
  const [age, setAge] = React.useState("");

  const handleChange = (event) => {
    setAge(event.target.value);
  };
  return (
    <div className={classes.root}>
      <CustomLabel text={"Relay:"} variant={"subtitle1"} />
      <FormControl className={classes.formControl}>
        <InputLabel id="demo-simple-select-label">Age</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          onChange={handleChange}
        >
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    </div>
  );
}

https://codesandbox.io/s/flex-align-items-gf5kf?fontsize=14&hidenavigation=1&theme=dark

Explore more about Flexbox resources: https://css-tricks.com/snippets/css/a-guide-to-flexbox/#align-items

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

Eliminate inner margin from the canvas of a bar chart created with ChartJS

I am looking to use Chart.js to create a single stacked bar chart that visualizes progress towards a specific financial goal. I have added a dotted line on top of the chart to represent this goal amount. The issue I am facing is that there is unwanted pad ...

What is the purpose of using 'ref' in conjunction with useCallback instead of just utilizing useCallback on its own?

While working on my React project, I came across some libraries that used 'useCallback' in a different way than I'm used to. Below is the code snippet showcasing this approach. Despite my initial thoughts, I still believe there's no sig ...

Using React to Render a Component with Local Storage Information

I'm in the process of developing a history list component for a form within a react application and encountering difficulties with local storage. The goal is to display a list of previous user inputs from the local storage data. My current approach i ...

In React Native, the onPress handler will continue to be triggered indefinitely after 2-3 presses

import firebase from './Firebase'; import { useState, useEffect } from 'react'; import { StyleSheet, Text, View, Button, FlatList } from 'react-native'; import { TextInput } from 'react-native-web'; import { setStatu ...

Facing an issue with the resolver type error when using React Hook Form with Yup

I'm currently working on an authentication form and I am using react-hook-form documentation as a reference to implement yup for input validation. The implementation appears to be similar to what's provided in the documentation, but I keep encoun ...

Guide to programmatically closing the TEMPORARY MUI DRAWER when an event finishes in a React application

I am currently implementing the MUI Drawer in my project, and I am facing a challenge with closing the drawer when a user-initiated event is completed. The issue lies in the fact that the component where the event is initiated and the component that render ...

I'm having trouble getting my MERN app to run on Heroku. Any suggestions on how to resolve this issue?

I recently used Brad Traversys Guide to create a basic MERN Stack App with React.js, Redux.js, Node.js, Express.js, and MongoDB using create-react-app and Mlab. The app functions perfectly on my local server without any issues, but I am facing difficulties ...

What are the key differences between using role and class selectors in HTML 5 and CSS3 to create two sidebars with three

My decision to eliminate all ids from my CSS and transition to HTML 5 has led me to question the use of roles in markup. In the past, IDs were used to style sidebars individually within a single selector for both. Here is an example: <div id="sidebar" ...

Jest: A runtime error occurred because the property being accessed is undefined

Currently, I am testing my React class which includes the import statement import dotnetify from "dotnetify";. While this works without any issues, Jest is reporting that dotnetify is undefined. Interestingly, when I switch the import to const do ...

Re-rendering multiple components with the new `use` feature in React version 18.3.0

When trying to fetch and use data using React 18.3.0, I encountered an issue with multiple re-rendering. react: 18.3.0-canary-3ff846d10-20230724 next: 13.4.12 The code for SuspenseTest component is causing multiple console outputs (about 5 to 8 times) be ...

Ensuring type safety in React using TypeScript

Within the code snippet below, I have specified that setLocale should be passed a value of type Locale through LocaleContextValue. However, why does the setLocale function not throw an error if no value is provided as a parameter? Even when I change it t ...

What is the method for retrieving the value of the Material-ui auto-complete component in a React.js

How can I retrieve the value of Material-UI auto-complete in react.js? I have tried productName: this.refs.productName.value productName: this.refs.productName.getValue() but neither of them seem to be working <AutoComplete hintText="Produ ...

Is there a way to resolve the issue of this div sticking to the top of the

I am currently working on building a portfolio website. One issue I'm facing is that my first div (for the "About Me" section) appears below my second div on the webpage. My goal is to have the first div displayed in full screen on both mobile and des ...

Is there a way to customize the font in the web inspector for Safari 8?

Is there a different method for modifying the css in Safari 8.0.2's Web Inspector on Yosemite 10.10.1? I've heard that editing /System/Library/PrivateFrameworks/WebInspector.framework/Versions/Current/Resources/Main.css has worked in previous ve ...

The rendered typeface may vary from the specified font family

I've encountered an issue with a font on my website. I'm using DIN Regular True Type Font and declaring it as follows: @font-face { font-family: 'DINRegular'; src: url('../fonts/DINBek-Regular.ttf') format('truetype ...

What steps do I need to take to successfully implement a log out and redirection feature using /api/logout in express with passport.js?

After setting up an endpoint /logout in Express, I specified that the route handler function should first log out and then redirect to the main page. index.js const express = require('express'); const mongoose = require('mongoose'); c ...

Upcoming accessibility challenges in MUI components

I'm currently in the process of developing a react application using MUI (Core & X) and encountering some challenges with WCAG Accessibility. Although I am utilizing various components provided by MUI, I am facing issues specifically with the data gri ...

Error: The default export is not a component compatible with React in the specified page: "/"

I'm facing an issue while building my next app. Despite using export default, I keep encountering an error that others have mentioned as well. My aim is to create a wrapper for my pages in order to incorporate elements like navigation and footer. vi ...

What is the recommended method for removing CSS classes in the Sencha ExtJS framework during a component event? (Those pesky red lines)

Occasionally, an aggravating red line will appear unpredictably when adjusting the size of this component using its split bar located at the top edge of the component. I managed to find a way to permanently eliminate the red line by removing its CSS class ...