How to style TextField used as Select of muiv5? - css

How to reduce the padding of TextField used as Select of muiv5. And Also the max-height of dropdown option plus the padding of individual list item of that dropdown.
I can't wrap my head around sx prop. Can someone please help me understand how to override styles uisng sx props. Thanks in advance.
const pageList = useMemo(() => {
return range(1, 100).map((item, i) => {
return (
<MenuItem
key={i}
value={item}
sx={{
'& .MuiMenuItem-root.Mui-selected': {
padding: '0px 40%',
},
}}
>
{item}
</MenuItem>
);
});
}, [lastPage]);
<TextField
InputLabelProps={{ shrink: false }}
margin="dense"
variant="outlined"
size="small"
select
value={currentPage}
onChange={(e) => {
const page = e.target.value ? Number(e.target.value) : 0;
onPageChange(page);
}}
sx={{
'&.MuiInputBase-input': {
padding: '10px',
},
'&.MuiList-root': {
maxHeight: '100px',
},
}}
>
{pageList}
</TextField>

Related

MUI 5 Tab Label Custom Thickness

I need to change the thickness of label inside a tab using MUI 5.
Here are what I tried:
interface TabPanelProps {
children?: React.ReactNode;
index: number;
value: number;
}
function TabPanel(props: TabPanelProps) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Box sx={{ p: 3 }}>
<Typography>{children}</Typography>
</Box>
)}
</div>
);
}
function a11yProps(index: number) {
return {
id: `simple-tab-${index}`,
'aria-controls': `simple-tabpanel-${index}`,
};
}
export default function UsersGroupsManagement() {
const [value, setValue] = React.useState(0);
const handleChange = (event: React.SyntheticEvent, newValue: number) => {
setValue(newValue);
};
const StyledTab = styled(Tab)<TabProps>(({theme}) => ({
'& .MuiButtonBase-root-MuiTab-root': {
fontWeight: 'bold'
}
}));
const styledLabel = styled('label')({
color: 'darkslategray',
backgroundColor: 'aliceblue',
padding: 8,
borderRadius: 4,
});
return (
<Box sx={styles.userAccounts}>
<Box sx={styles.tabbox}>
<Tabs value={value} onChange={handleChange} aria-label="User Management Tabs" >
<Tab label="ADD NEW USER" {...a11yProps(0)} sx={{
'& .MuiButtonBase-root-MuiTab-root': {
color: 'black',
backgroundColor: 'red',
fontWeight: 'bold'
}
}}/>
<Tab label="MANAGE USERS" {...a11yProps(1)} sx={{
'& .MuiButtonBase-root-MuiTab-root': {
fontWeight: 'bold'
}
}}/>
</Tabs>
</Box>
<TabPanel value={value} index={0}>
<AddNewUser />
</TabPanel>
<TabPanel value={value} index={1}>
Item Two
</TabPanel>
</Box>
);
}
I tried to create a StyledTab but didnt work.
I tried to create a styled label didnt work at all.
I tried to give css from sx props using but didnt work.
Can you please explain me how can I manage to make thicker labeled tabs in Material UI v5?
u can follow something like this..
<Tabs
sx={{
"& .MuiTabs-indicator": { backgroundColor: "#E86826" },
"& .MuiTab-root.Mui-selected": { color: "#E86826", fontWeight:"700" },
}}
value={value}
onChange={handleChange}
aria-label="nav tabs example"
centered
>
Just Edit the tabs and u work is done...hope it helps

Only Show Text on Selection - MUI

I only want to show the text of the tab on selection.
This is from the MUI documentation. How can I only show labels on selection? I assume I can use the state below and translate it somehow, how on the selection the color appears with the element.
Please see the code where I have tried to establish. I am new to this framework. If anyone can provide tips let me know!
function TabPanel(props) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`vertical-tabpanel-${index}`}
aria-labelledby={`vertical-tab-${index}`}
{...other}
>
{value === index && (
<Box sx={{ p: 3 }}>
<Typography>{children}</Typography>
</Box>
)}
</div>
);
}
TabPanel.propTypes = {
children: PropTypes.node,
index: PropTypes.number.isRequired,
value: PropTypes.number.isRequired,
};
function a11yProps(index) {
return {
id: `vertical-tab-${index}`,
'aria-controls': `vertical-tabpanel-${index}`,
};
}
//
const JobPostBuild = () => {
const [value, setValue] = React.useState(0);
const handleChange = (event, newValue) => {
setValue(newValue);
};
return (
<Box
sx={{ flexGrow: 1, bgcolor: 'gray', display: 'flex', height: 500 }}
>
<Tabs
orientation="vertical"
variant="scrollable"
centered
value={value}
onChange={handleChange}
sx={{ borderRight: 1, borderColor: 'divider' }}
>
<Tab icon={<WorkIcon/>} label={"Role"} {...a11yProps(0)} />
<Tab icon={<AccountBoxIcon/>} label="People" {...a11yProps(1)} />
<Tab icon={<ViewCompactIcon/>} label="Build" {...a11yProps(2)} />
<Tab icon={<PostAddIcon/>} label="Post" {...a11yProps(3)} />
</Tabs>
<TabPanel value={value} index={0}>
Role
</TabPanel>
<TabPanel value={value} index={1}>
People
</TabPanel>
<TabPanel value={value} index={2}>
Build
</TabPanel>
<TabPanel value={value} index={3}>
Post
</TabPanel>
</Box>
);
}
export default JobPostBuild
Happy to discuss this over Discord please let me know!
You can check the value of selected tab to set a condition for displaying tab label:
<Tab label={value === 0 ? "Role" : ""} {...a11yProps(0)} />
Demo

How to override .MuiSelect-nativeInput in Material-UI

const styles = makeStyles((theme) => ({
root: { margin: "0px 20px" },
textStyle: {
fontFamily: "Comfortaa",
},
container: {},
textField: {
fontFamily: "Comfortaa",
},
dropDownFormSize: {
width: "100%",
fontFamily: "Comfortaa",
},
optionDropdown: {
color: "black",
},
dropDownSelector: {
color: "black",
backgroundColor: "tomato",
},
nativeInput: {
opacity: "1",
},
}));
const MainTable: React.FC = () => {
const classes = styles();
<FormControl
classes={{
root: classes.dropDownFormSize,
}}
>
<Select
required
className={classes.dropDownSelector}
value={emotion[i]}
name="emotion"
onChange={handleChangeEmotion(i)}
classes={{
root: classes.optionDropdown,
select: classes.optionDropdown,
// using nativeInput here gives me error
nativeInput: classes.nativeInput,
}}
MenuProps={{
anchorOrigin: {
vertical: "bottom",
horizontal: "left",
},
getContentAnchorEl: null,
MenuListProps: {
className: classes.optionDropdown,
},
}}
placeholder="Select Something"
native={false}
>
<MenuItem
value=""
disabled
// className={
// classes.optionItems
// }
>
Select Emotion
</MenuItem>
{emotions.map((emotion, i) => {
return (
<MenuItem
key={i}
// className={
// classes.optionItems
// }
value={emotion}
>
{emotion}
</MenuItem>
);
})}
</Select>
</FormControl>;
};
I want to remove opacity from the .MuiSelect-nativeInput Class. When I try to override this class using the nativeInput rule, I get this error message :-
Object literal may only specify known properties, and 'nativeInput' does not exist in type 'Partial<ClassNameMap<SelectClassKey>>'. Eventhough, nativeInput rule is given in the documentation of Select API. I have tried to override it in the Theme file but again, I get the error that nativeInput does not exist. How can I remove the opacity from the MuiSelect-nativeInput class.
You can instead use a TextField rendered as a select input.
const useStyles = makeStyles({
root: {
"& .MuiSelect-nativeInput": {
opacity: 1,
},
},
});
<TextField
select
classes = {{ root: classes.root }}
/>

Change the color of MUI Autocomplete option

I'm using the Autocomplete of Material UI and I have a list with the attribute Color. I have to render option by option with the respective color in option background.
Here's a example:
import React from "react";
import TextField from "#material-ui/core/TextField";
import Autocomplete from "#material-ui/lab/Autocomplete";
export default function ComboBox() {
return (
<Autocomplete
id="combo-box-demo"
options={top100Films}
getOptionLabel={option => option.title}
style={{ width: 300 }}
renderInput={params => {
return (
<TextField
{...params}
label="Combo box"
variant="outlined"
fullWidth
/>
);
}}
/>
);
}
const top100Films = [
{ title: "The Shawshank Redemption", year: 1994, color: '#FF0000' },
{ title: "The Godfather", year: 1972, color: '#FF5555' },
{ title: "Avatar", year: 2010, color: '#FFFFFF' },
// Plus a bunch more
];
You can use renderOption to render the style conditionally for each option in the latest version of MUI.
<Autocomplete
renderOption={(props, option) => {
const { title, color } = option;
return (
<span {...props} style={{ backgroundColor: color }}>
{title}
</span>
);
}}
{...}
/>
Live Demo
You can change the CSS like this:
.MuiAutocomplete-inputRoot[class*="MuiOutlinedInput-root"] {
background: #ffff
}
This will to change the options color.
In the code, the sx prop I have included the css properties for the whole option menu, selected option and while hovered in the selected option for the Autocomplete component:
<Autocomplete
limitTags={1}
disablePortal
id="simple-search"
value={select.region}
onChange={handleChange("region")}
options={region}
sx={{
width: { sm: "100%", md: 340 },
"& + .MuiAutocomplete-popper .MuiAutocomplete-option": {
backgroundColor: "#363636",
},
"& + .MuiAutocomplete-popper .MuiAutocomplete-option[aria-selected='true']":
{
backgroundColor: "#4396e6",
},
"& + .MuiAutocomplete-popper .MuiAutocomplete-option[aria-selected ='true']
.Mui-focused":
{
backgroundColor: "#3878b4",
},
}}
disableCloseOnSelect
multiple
renderInput={(params) => (
<TextField {...params} label="Region" color="info" />
)}
/>

How to change the position of an Icon component, within a Tab component?

I'm using MaterialUI's tabs in my React project.
This is the JSX for the tabs:
<AppBar color="default" position="static">
<Tabs indicatorColor="primary" textColor="primary" value={tabIndex} onChange={this.handleChange}>
{instances.map(instance =>
<StyledTab
style={{ textTransform: 'initial' }}
onClick={() => { this.changeActiveInstance(instance.id) }}
label={this.getTabAddress(instance)}
icon={<ClearIcon ></ClearIcon>}
>
</StyledTab>
)}
</Tabs>
This is how i inject the css:
const StyledTab = withStyles({
root: {
textTransform: 'initial'
},
})(Tab);
The result is this:
I would like to position the "ClearIcon" elsewhere. I tried playing with the style injection a bit, with no success.
Can somebody point me to the right direction?
When trying to customize any Material-UI component, the starting point is the CSS portion of the API documentation. The most relevant classes that you may want to override in this case are wrapper, labelContainer, and label.
The best way to fully understand how these are used and how they are styled by default (and therefore what you may want to override) is to look at the source code.
Here are the most relevant portions of the styles from Tab.js:
/* Styles applied to the `icon` and `label`'s wrapper element. */
wrapper: {
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
width: '100%',
flexDirection: 'column',
},
/* Styles applied to the label container element if `label` is provided. */
labelContainer: {
width: '100%', // Fix an IE 11 issue
boxSizing: 'border-box',
padding: '6px 12px',
[theme.breakpoints.up('md')]: {
padding: '6px 24px',
},
},
And here is the relevant code for understanding how these are used:
if (labelProp !== undefined) {
label = (
<span className={classes.labelContainer}>
<span
className={classNames(classes.label, {
[classes.labelWrapped]: this.state.labelWrapped,
})}
ref={ref => {
this.labelRef = ref;
}}
>
{labelProp}
</span>
</span>
);
}
<span className={classes.wrapper}>
{icon}
{label}
</span>
Below are some examples of possible ways to customize this.
import React from "react";
import PropTypes from "prop-types";
import Paper from "#material-ui/core/Paper";
import { withStyles } from "#material-ui/core/styles";
import Tabs from "#material-ui/core/Tabs";
import Tab from "#material-ui/core/Tab";
import PhoneIcon from "#material-ui/icons/Phone";
import FavoriteIcon from "#material-ui/icons/Favorite";
import PersonPinIcon from "#material-ui/icons/PersonPin";
const styles = {
root: {
flexGrow: 1,
maxWidth: 700
},
firstIcon: {
paddingLeft: 70
},
labelContainer: {
width: "auto",
padding: 0
},
iconLabelWrapper: {
flexDirection: "row"
},
iconLabelWrapper2: {
flexDirection: "row-reverse"
}
};
class IconLabelTabs extends React.Component {
state = {
value: 0
};
handleChange = (event, value) => {
this.setState({ value });
};
render() {
const { classes } = this.props;
return (
<Paper square className={classes.root}>
<Tabs
value={this.state.value}
onChange={this.handleChange}
variant="fullWidth"
indicatorColor="secondary"
textColor="secondary"
>
<Tab
icon={<PhoneIcon className={classes.firstIcon} />}
label="Class On Icon"
/>
<Tab
classes={{
wrapper: classes.iconLabelWrapper,
labelContainer: classes.labelContainer
}}
icon={<FavoriteIcon />}
label="Row"
/>
<Tab
classes={{
wrapper: classes.iconLabelWrapper2,
labelContainer: classes.labelContainer
}}
icon={<PersonPinIcon />}
label="Row-Reverse"
/>
<Tab icon={<PersonPinIcon />} label="Default" />
</Tabs>
</Paper>
);
}
}
IconLabelTabs.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(IconLabelTabs);
We have a inbuilt property to set the icon position of tab in material ui. Document link
iconPosition:'bottom' | 'end' | 'start' | 'top'

Resources