Media query in jss not responive - css

I am using style props in my react element with #media query. But for some reason it isn't responding. I am using JSS. Here is my code
const style = {
usernameConatiner: {
display: "flex",
alignItems: "center",
backgroundColor: "red"
},
"#media screen and minWidth(32em)": {
usernameConatiner: {
backgroundColor: "blue"
}
}
}
There is obviously a whole bunch of other css rules in the middle. I have also tried to nest the media query which isn't working either.
It is rendered in the following way
<div style={styles.usernameConatiner} />
Am I missing something very obvious here?

It's happening because your media query is not being defined correctly on the styles object.
The correct media query would be #media screen and (min-width: 32em), notice min-width: 32em is inside the parenthesis, and also notice that is written as min-width (separated with a dash) instead of minWidth (camelCase)
Check it working on CodePen: https://codepen.io/anon/pen/yGEXox
To summarize, your styles object should look like this:
const style = {
usernameContainer: {
display: 'flex',
alignItems: 'center',
backgroundColor: 'red'
},
'#media screen and (min-width: 32em)': {
usernameContainer: {
backgroundColor: "blue"
}
}
}
Hope this works for you.

As you already are in JS and want to write a style that depends on width, wouldn't be easier to get the window.width and define your style objects accordingly?
Always remembering you may use window.addEventListener('resize', this.updateWindowWidth); to handle the changes.

Two things here.
Your media query syntax is not correct.
You can't use media queries / pseudo selectors like &:hover, &:disabled and so on in JSS (CSS in JS) directly. To do this, you must install a thrid party package Radium https://www.npmjs.com/package/radium
Installation - npm install --save radium
How to use it?
Once you install radium, your entire app should be enclosed with <StyleRoot/> which is a named export from radium. The best place to do this is in index.js.
index.js
import { StyleRoot } from "radium";
ReactDOM.render(
<StyleRoot>
<App />
</StyleRoot>,
document.getElementById("root")
);
You now need to wrap the component that you are using your media queries in with Radium like this. This can be done for both class and functional components.
MyComponent.js
import Radium from 'radium'
function MyComponent(){
const myStyle = {
color: 'blue',
backgroundColor : 'red',
// media query
"#media (max-width: 1100px)": {
color:'orange',
backgoundColor : 'black'
},
}
return (
<p style = {myStyle}>Enter your text here</p>
)
}
export default Radium(MyComponent);

Related

How to use #media to change width in prop styled components

I am not sure if what they called but I have a component which takes its style as an object with its props.
const PricingSection = ({
secDesc,
}) => {
return (
<Text
{...secDesc}
content={intl.formatMessage({ id: 'packages.description' })}
/>
);
};
PricingSection.propTypes = {
secDesc: PropTypes.object
};
PricingSection.defaultProps = {
secDesc: {
width: '50%',
m: 'auto',
textAlign: 'center',
pt: '20px',
color: '#6a7a8d',
lineHeight: '1.5rem',
},
}
I want to apply different witdh for mobile devices. I know how to use #media tag in css but I dont know where to write #media in this component or how achieve what I want.
Instead of passing style object, it would be better if you apply a class to the component for easy maintenance. It'll also solve your problem for width for different size devices as you can add media query for the class in its css file.
Another suggestion would be to use styled-components. They provide great support for adding media queries inside the component file.
Refer:styled-components
you can use 'react-device-detect' and pass the different width from parent component like this:
enter code here
import isMobile from 'react-device-detect'
secDesc: {
width: isMobile ? '50%' : 'your value',
m: 'auto',
textAlign: 'center',
pt: '20px',
color: '#6a7a8d',
lineHeight: '1.5rem',
}
< PricingSection
secDesc={secDesc}
/>

React Material UI DataGrid style MuiDataGrid-window within createMuiTheme or makeStyles / styled

I'm trying really hard to change the css for the .MuiDataGrid-window in MatierialUi DataGrid.
Therefore I was following css rules from https://material-ui.com/api/data-grid/
I tried it within createMuiTheme for root it was working fine, but not for window. I also tried a lot of different cominations like MuiDataGrid-window or only 'MuiDataGrid-window' directly under overrides, but nothing worked..
export const theme = createMuiTheme({
overrides: {
MuiDataGrid: {
root: {
backgroundColor: 'red',
},
window: {
width: '120%',
},
},
}
});
Next try was a styled DataGrid component, which also didn't work out.
Both didn't work. A styled component would be my prefered way!
const StyledDataGrid = styled(DataGrid)({
MuiDataGrid: {
root: {
backgroundColor: 'green',
},
window: {
width: '120%',
}
}
});
Maybe I'm completely on the wrong way.. But how to style the CSS attributes in MUI's API like .MuiDataGrid-mainGridContainer, .MuiDataGrid-overlay, .MuiDataGrid-columnsContainer, .MuiDataGrid-colCellWrapper etc.
Thanks a lot and maybe it is helpful for somebody else :)
If you check the styles applied, window class element has two selectors associated (multiple classes):
.MuiDataGrid-root .MuiDataGrid-window
To apply the styles in children elements, such as, window in grid root, you need to select both of them:
MuiDataGrid: {
root: {
backgroundColor: 'red',
'& .MuiDataGrid-window': {
backgroundColor: 'green'
}
}
}
In documentation the grid component have just one rule name: root

Override React AgGrid styling settings using createStyles and withStyles

I'm aware that it's possible to override Ag Grid properties by editing the CSS itself, however I'm wondering if it's possible to use the functionalities built into react to do this instead. I'm relatively new to the two frameworks, so apologies if there's something I'm not understanding.
Ultimately, what I want to do is something like this:
styles.js
---------
const styles = (theme: Theme) =>
createStyles({
root: {
position: 'relative',
height: 'calc(100vh - 128px)',
},
agHeaderCellLabel: {
agHeaderCellText: {
writingMode: 'vertical-lr',
marginTop: '100px',
},
},
})
export default styles
GridComponent.tsx
-----------------
import styles from './styles'
...
return (
<Paper className={classes.root}>
<div
id="myGrid"
style={{
height: '100%',
width: '100%',
}}
className={`ag-theme-material ${classes.agHeaderCellLabel}`}
>
<AgGridReact
// listening for events
onGridReady={onGridReady}
onRowSelected={onRowSelected}
onCellClicked={onCellClicked}
onModelUpdated={calculateRowCount}
// Data
columnDefs={cDef}
defaultColDef={defaultColumnFormat}
suppressRowClickSelection={true}
groupSelectsChildren={true}
debug={true}
rowSelection="multiple"
// rowGroupPanelShow={this.state.rowGroupPanelShow}
enableRangeSelection={true}
pagination={true}
rowData={rows}
/>
</div>
</Paper>
)
...
export withStyles(styles)(GridComponent)
In this example I'm just trying to get the header text to be displayed vertically.
I've inherited this project, and I've noticed that all of the styling has been done in this method, as there are no custom css files lying around, so I'm trying to stick with that convention of a styles file alongside the component.
Is this possible, and if so,
I ran into this same situation, and came up with the following solution. Although not necessarily ideal, it allows you to continue with the desired convention.
styles.js
---------
const styles = (theme: Theme) =>
createStyles({
root: {
position: 'relative',
height: 'calc(100vh - 128px)',
},
//Apply changes to agGrid material HeaderRoot
myClassAppliedToGrid: {
'& .ag-header[ref="headerRoot"]':{
writingMode: 'vertical-lr',
marginTop: '100px',
}
}
//OR
//Apply Changes to agGrid material header row
myClassAppliedToGrid: {
'& .ag-header-row':{
writingMode: 'vertical-lr',
marginTop: '100px',
}
}
})
export default styles
The key idea is using the & SASS syntax to "reach into" agGrid and make more specific CSS classes so you can override them. (see https://css-tricks.com/the-sass-ampersand/ for more info)
The key pieces of info are:
.parent {
& .child {}
}
turns into
.parent .child {}
and
.some-class {
&.another-class {}
}
turns into
.some-class.another-class { }
Using this sytanx, you should be able to create CSS classes that you can apply to your grid, columns, rows, etc that will properly override the material ag-grid theme.
Here is another example, but this class gets applied to a cell using agGrid cellStyleRules when a row is dragged over it, rather than applying the class to the grid as a whole. This way it only effects cells that have a row drag occuring over them:
rowDraggedOverCellsTopEdge: {
'&.ag-cell': {
borderTopColor: theme.palette.gray[50],
borderTopWidth: 8,
backgroundColor: fade(theme.palette.gray[50], 0.3)
}
},
Finally, one thing I did not do but would reccommend investigating is looking into agGrid's theme overriding, especially if you are on version 23+
https://www.ag-grid.com/javascript-grid-themes-provided/#customising-themes
It might be a good idea to get your base overrides to the theme done this way if you expect a consistent look and feel of your grids throughout the application.
Cheers!

Override components like MuiTab that use media queries

I'm trying to provide CSS overrides for MuiTab to increase the font-size.
Using the documentation about CSS overrides on material-ui I've managed to increase font size for most elements, however I got stuck at elements that use media queries as they produce more specific CSS rules than the ones I provide with my overrides.
theme.ts :
import { createMuiTheme } from '#material-ui/core';
const fontSizeStyle = {
fontSize: '1rem',
};
const fontFamilyStyle = {
fontFamily: '"Ubuntu", sans-serif'
};
const theme = createMuiTheme({
overrides: {
MuiTab: {
root: {
...fontFamilyStyle,
...fontSizeStyle,
},
label: fontSizeStyle,
},
}
});
export default theme;
This produces following css rules applied to a MuiTab:
The rule is generated by the following file:
https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/Tab/Tab.js
[theme.breakpoints.up('md')]: {
fontSize: theme.typography.pxToRem(13),
},
Does anyone have an example how to override this media query using createMuiTheme function? I don't have the breakpoints, so perhaps I need to specify breakpoints as well to be able to use them in my overrides
Kind regards
I solved it by specifying it in the following way:
MuiTab: {
root: {
minWidth: 0,
'#media (min-width: 0px)': {
minWidth: 0
}
}
}
Specify it as follows
let theme = createMuiTheme({});
theme = {
...theme,
overrides: {
MuiTab: {
root: {
[theme.breakpoints.up("xs")]: {
minHeight: 10
}
}
}
}
}
export default theme;
theme.breakpoints exposes four helper methods to create CSS media queries:
theme.breakpoints.up(key)
theme.breakpoints.down(key)
theme.breakpoints.only(key)
theme.breakpoints.between(start, end)
Where each key is a breakpoint and matches with a fixed screen width.
Allowed key values are xs|sm|md|lg|xl
See material-ui docs for more info
I also faced the same issue. I read the docs about Breakpoints and find a way for this situation but I find it kinda ugly as I have to apply the overridden styles in each Tab using classes property.
Note: I don't know the solution for this problem using createMuiTheme function
Apply the style to the breakpoints style. In this case,
const styles = theme => ({
mediaFont:{
[theme.breakpoints.up('md')]: {
fontSize:fontSizeStyle.fontSize,
},
},
});
Apply the above style to TabLabel
<Tab label="Item One" classes={{label:classes.mediaFont}} />
CSS has a mechanism for forcing a less specific rule to override a more specific one: !important.
const fontSizeStyle = {
fontSize: '1rem !important',
};

React-JSS Media Query does not work with chrome mobile emulator

I am using JSS in my React project and I encountered strange issue, which I find hard to solve. Basically I write media query and it is triggered when I shrink my desktop browser. Though while using device toolbar, it does not seem to work. I am trying to hide span when device "width" is smaller than 600px. Any help will be appreciated.
Here is the code:
const menuStyles = theme => ({
flex: {
display: 'flex',
alignItems: 'center',
},
wrapper: {
composes: '$flex',
cursor: 'pointer',
},
span: {
fontFamily: theme.fontMontserrat,
marginRight: '30px',
},
'#media screen and (max-width: 600px)': {
span: {
display: 'none',
},
},
});
Ok, fixed the problem. It was in a completely different part of application.
I forget to add this line in my code:
<meta name=viewport content="width=device-width,initial-scale=1">
You can always check the generated CSS, if it is what you expect it to be then you have wrong assumptions about CSS/html. At the end, jss does nothing else than generating regular CSS.

Resources