How to modify the z-index of Material-UI <Select> dropdown div? - javascript

I am rendering an <AppBar> with a large z-index value (using withStyles, it has a value of theme.zIndex.modal + 2 which computes to 1202).
The reason for this is to ensure my <Drawer> component remains hidden behind the <AppBar> when it's opened (i.e. a clipped drawer).
However when I render a <Select> component within my appbar, the 'dropdown' div does not have a large enough z-index value to be displayed, and so it ends up being hidden behind the appbar.
A basic example is as follows:
let Test = ({classes}) => (
<AppBar className={classes.appbar} elevation={2} position='relative'>
<Toolbar>
<Select>
<MenuItem>{"Item 1"}</MenuItem>
<MenuItem>{"Item 2"}</MenuItem>
</Select>
</Toolbar>
</AppBar>
)
const styles = theme => ({
appbar: {
zIndex: theme.zIndex.modal + 2,
margin: 0
}
})
Test = withStyles(styles)(Test);
Overriding the z-index on any of <Select>'s exposed classes does not seem to fix my problem. How can I ensure <Select> appears in front of <AppBar>?

You can use the style attribute on all components in Material-UI
<Select style={{zIndex: X}}>
...
</Select>
Cf: https://v0.material-ui.com/#/components/select-field
For details about all the available styles attributes.

You can use PaperProps on Drawer component to adjust zindex instead of changing Select component's zindex.

Related

How to map each div with different width in react?

I have a weird problem. I'm mapping options for a submenu inside of a div (container for the submenu). And I set width of the DIV to be '100%'. However, the following submenu divs take the same width, even though they do not need it.
I have provided some screenshot to describe it better. You see the first submenu reaches max-width which is 400. And automatically, the second div has 400px width even though it clearly does not need it.
I tried using width='fit-content', or not assigning width ( so that it calculates it itself ). But they do not help at all, the submenu collapses completely and has like 50px width - which is unreadable.
Is there any way to achieve different width for all the submenus?
EDIT (code):
{showNestedOptions && (
<Box
w="100%"
maxW="400px"
>
{map(props.data.nestedOptions, (nestedOption, index: number) => {
return (
<Box>
<Option textAlign="left">
<Box h={'100%'} whiteSpace="normal">
{label}
</Box>
</Option>
</Box>
);
})}
<Box> = <div>
<Option> = <option>
all the options have the width of the widest element, and I'd like them to each adapt to the biggest element of each submenu

When should I use style instead of sx prop in Material-UI?

The style and sx prop in MUI components pretty much do the same thing. The sx prop offers a few shorthand syntaxes, and allows you to access the theme object. But apart from that, they seem identical. When are you supposed to use one over the other?
To really understand which one to use, we need to understand what's happening under the hood. Material UI uses emotion(, or whatever styling engine you chose manually), in order to style its components. On the surface, the following two might seem to be doing the same thing:
<Box sx={{ height:'50px', width:'25px' }}/>
<div style={{ height:'50px', width:'25px' }}/>
Both render divs with the required height and width, to the DOM. But for the div, the styles are applied as inline styles, whereas the Box applies the styles in the form of a class, to the div element. The class definition itself, is stored in the head tag, which you can inspect, to see the following
This is all well and fine, as long as we're declaring the styles only once. But stuff really goes crazy when you add dynamic styling. Perhaps there is a state variable controlling the height of your div.
function CustomComponent(){
const [computedHeight,setComputedHeight]=useState();
useEffect(()=>{
window.addEventListener('resize',()=>setComputedHeight(window.innerWidth/2))
},[]);
return (
<Box sx={{ height:computedHeight, width:'25px'}}/>
<div style={{ height:computedHeight, width:'25px'}}/>
)
This is a common scenario, where some external variable(the width of the browser window for eg.) determines some property of your component. What happens is every time this state changes into a new value, MUI creates a new class, sets it as the class for the Box, and adds the definition to the <head> tag of your website, as a brand new <style> tag. So in very little time, the head tag fills up with hundreds of style tags, which is clearly undesirable.
However, in the case of your div tag, the styles are located inline. So no matter if the value changes once, or a hundred times, there is only one definition of the style, and it exists on the element itself. No need to worry about it.
EDIT 1:
MUI creates a new style tag only for a style that hasn't been used before. To illustrate, if your sx prop dynamically changes the color between 'red' and 'blue' like this,
sx={{
color: dynamicValue ? 'red' : 'blue',
}}
MUI will only create two tags(for the two possible values of color), no matter how many times you change the value of dynamicValue. MUI will just use the old style tags.
Note on Pseudo selectors:
Another thing to note is that inline styles cannot make use of pseudo elements(like ::after, or ::before), or pseudo classes(like :hover, :focus etc.), as inline styles directly affect the current element. You would have to employ a workaround like css variables in order to change the styles on pseudo elements/classes.
TLDR; Put your dynamic styles(the ones that change based on some variable) in the style prop, and put all the static styles in the sx prop
style vs sx in MUI 5
Sandbox Link
sx prop works only on MUI components like Grid, Box and so on, whereas style prop works on both MUI components and HTML like elements (JSX) such as span, article,h1 and so on.
sx prop is very helpful when compared to style prop in some cases as explained below. There might be many differences between them but these are the 3 key differences I have noticed and you might encounter them often.
Defining Media queries
Nesting styles
Making use of theme parameter (to get palette) inside sx object which we can't do in style like this - color: (theme) => theme.palette.primary.main
1. Defining Media queries
One difference between style and sx which is most popular is, defining media queries based on the Material UI theme.
How would you deal with media queries in style prop? You can use your own breakpoints and do it the way you do in CSS for sure, but you cannot use Material UI breakpoints.
This is where sx prop comes in handy where you can define media queries and other MUI provided properties to alter your styles.
Example
import { Typography, createTheme, ThemeProvider } from '#mui/material'
let theme = createTheme()
function Demo() {
const stylePropCSS = {
backgroundColor: 'lightblue',
/* theme prop is not understood here,
so this breakpoint will not work,
and text will not turn into orange */
[theme.breakpoints.down('xl')]: {
backgroundColor: 'orange',
},
}
/* theme prop is understood here.
breakpoints can be applied here based on MUI theme
*/
const sxPropCSS = {
backgroundColor: 'lightgreen',
[theme.breakpoints.up('xs')]: {
backgroundColor: 'orange',
},
}
return (
<ThemeProvider theme={theme}>
{/* style prop */}
<Typography style={stylePropCSS}>
This text will <b>NOT TURN</b> orange as
I am using style prop and MUI 'theme' is not understood
</Typography>
<br />
{/* sx prop */}
<Typography sx={sxPropCSS}>
This text will <b>TURN</b> into orange as
I am using sx prop and MUI 'theme' is understood
</Typography>
</ThemeProvider>
)
}
export default Demo
2. Nesting styles and using theme inside sx prop
You can nest the styles when using sx prop, but can't do this when using style prop.
With sx prop
<Box sx={styles.post}>
<Typography variant="h4">This is the title</Typography>
</Box>
Box is a div of background black, and I need h4 to be yellow OR MUI primary color. With this requirement, I can nest my styles when I use sx prop like this where I place h4 inside post and define sx only on Box
const styles = {
post: {
backgroundColor: 'black',
// nesting h4 inside post
h4: {
// color:'yellow' // OR
color: (theme) => theme.palette.primary.main,
/* I cannot use theme inside style object. Since I am going
to apply styles.post to sx prop,I could make use of theme
object here as an argument */
},
},
}
With style prop
<Box style={styles.post}>
<Typography variant="h4" style={style.heading}>
This is the title
</Typography>
</Box>
const styles = {
post: {
backgroundColor: 'black',
},
// I can't nest the heading inside post, so defining it outside post
heading: {
color: 'yellow',
// color: (theme) => theme.palette.primary.main, // THIS WON'T WORK with style prop
},
}

How to make recharts custom tooltip to be clickable?

As i was trying to add link in my custom tooltip of recharts, i can not able to hover on tooltip content it will be hidden automatically, is there any props that i need to override for of recharts to make it clickable?.
Below is my tooltip
<Tooltip content={(value)=>renderTooltip(value)} />
Below is my renderTooltip which i am using it
const renderTooltip = (props) => {
if (props.active) {
return (
<div >
<div className="tool-tip">
<span className="tool-tip-footer">
{' '}
Google
</span>
</div>
</div>
);
}
I got this working by doing adding trigger='click' prop and adding a style pointer-events: auto to the parts of the tooltip I wanted to be clickable.
The recharts tooltip wrapper has pointer-events: none which prevented clicking it even after changing the trigger.
The Tooltip component calculates internally if the content has to be shown or not, so you don't have to. This might be causing some issues beyond your control.

ReactJS - Responsive Layout using Media Queries

I am working on a web app, and I am trying to make it responsive, but I am running into a few problems. I am using media queries to detect if the screen width is > than a certain amount or < than a certain amount. Based on that, I would want to change the layout of my component, so that it does not cram and move everything out of alignment. However, it seems like if my goal is to reorder the child components within my component using conditional rendering based on the media query result, then my code would be repeated multiple times. Hence, I am checking to see if there are any other ways to accomplish this.
Below is a screenshot of the browser when the screen size gets smaller, the contents get too cramped up, and hence it messes up the alignment.
Below is a snippet of my code (this code represents the right side of the image -> Revenue and Revenue KPI)
<Row justify="space-around">
<Col span={11}>
<Statistic
title="Revenue"
value={data[metric].revenue}
valueStyle={{ color: '#3f8600' }}
/>
</Col>
<Divider type="vertical" />
<Col span={11}>
Revenue KPI
<Button shape='circle' size='small' onClick={() => handleClick('rev', metric, 'post')} style={{ marginLeft: '5%' }}>
<PlusOutlined />
</Button>
<Statistic
value={data[metric].rev_kpi}
valueStyle={{ color: '#3f8600' }}
/>
</Col>
</Row>
What I would want to do, is to change the grid layout once the screen width is smaller than a certain amount, and instead of the components above being in the same Row, I would want each to be in their Row (stacking on top of each other). However, if I were to do this using conditional rendering, it seems like I would have to repeat the code quite a fair bit, which seems tedious and messy. Hence, I am hoping if there are any more efficient methods to achieve what I would want to make.
The UI package I am using is AntD (where I got the components for Row, Col, Statistic, Button)
https://ant.design/components/grid/
this is my media query function (I use this function to return a boolean based on the query I pass in)
import { useEffect, useState } from "react";
function useMediaQuery(
query,
defaultMatches = window.matchMedia(query).matches
) {
const [matches, setMatches] = useState(defaultMatches);
useEffect(() => {
const media = window.matchMedia(query);
if (media.matches !== matches) setMatches(media.matches);
const listener = () => setMatches(media.matches);
media.addListener(listener);
return () => media.removeListener(listener);
}, [query, matches]);
return matches;
}
export default useMediaQuery;
All help is appreciated, thanks all! Do guide me along as I am new to React and especially new to implementing responsive websites!
Since Row and Col in ant design seems to be based on flex you should try to use the CSS order property to re-arrange your elements
https://developer.mozilla.org/en-US/docs/Web/CSS/order
It is also available as a prop on the Col component:
https://ant.design/components/grid/#Col
CSS order demo (use media query to change order value for various screen sizes):
div {
display: flex;
flex-direction: column;
}
#reverse:checked ~ div>p:first-child {
order: 2;
}
<input type="checkbox" id="reverse"/>
<label for="reverse">reverse</label>
<div>
<p>First text element in HTML</p>
<p>Second text element in HTML</p>
<div>
For even more complex rearrangement of your elements you could use CSS Grid:
grid-template-areas: give custom names to areas in your grid
grid-area: place element in the grid using one of your custom names
use media-queries to change grid-template-areas and it should work nicely
https://css-tricks.com/snippets/css/complete-guide-grid/

react native how to custom style with props

I am trying to make a custom button component and change the style of the button using props. Below is my code:
class CustomButton extends React.Component {
render() {
return (
<TouchableOpacity
style={{height:this.props.height, borderWidth:1}}>
<Text style={{fontSize:13}}>{this.props.text}</Text>
</TouchableOpacity>
)
}
}
And I call my component like this:
<CustomButton
// custom text using props works fine
text="whatever I want to say"
// But changing custom style won't work.
height='200' or 200
/>
I am able to change the text using props however, when I apply the same to change the height it won't work. How could I change the style using props?
Try using:
<CustomButton
text="whatever you want to say"
height={200}
/>
hope it works
Not enough points to comment, can you try sending
<CustomButton
text="....."
height='200px'
/>
The reason being the style is expecting 200px as height px being one of the key metric.
There are other metrics such as px, em, vw, etc check w3 units for css

Categories

Resources