Reputation: 3
I want to add a media query in react to check the size of the screen before applying width.
This is my code :
const myConfig = {
nodeHighlightBehavior: true,
node: {
color: "lightgreen",
size: 120,
highlightStrokeColor: "blue",
labelProperty: "name"
},
link: {
highlightColor: "lightblue"
},
@media (max-width: 960px){
width: window.innerWidth * 0.9
};
Error: Line 76: Parsing error: Stage 2 decorators disallow object literal property decorators
Upvotes: 0
Views: 254
Reputation: 1575
You could create a higher order component (HOC) to solve this issue. Using something like the react-media library (you would need to install the react-media library) one could have the following:
import React from 'react';
import Media from 'react-media';
class OriginalComponent extends React.Component {
render() {
const myConfig = {
nodeHighlightBehavior: true,
node: {
color: "lightgreen",
size: 120,
highlightStrokeColor: "blue",
labelProperty: "name"
},
link: {
highlightColor: "lightblue"
}
}
if (this.props.small) {
myConfig.width = window.innerWidth * 0.9
}
return (
<div style={myConfig} />
)
}
}
class App extends React.Component {
render() {
return (
<div>
<Media query="(max-width: 960px)">
{matches =>
<OriginalComponent small={matches} />
}
</Media>
</div>
);
}
}
But having a HOC might be a little overkill for your usage.
Upvotes: 0
Reputation: 536
You must import that from file.css because CSS in JS
don't support it, then use className
.
Else, you can use react-responsive
Upvotes: 0
Reputation: 398
Media queries are a CSS property and you are using it as a JavaScript attribute.
You either need to write the media query on CSS and apply it to a component, perhaps a global wrapper component.
Or you use JavaScript to get the width of the page and then set it on your myConfig, for this you can use DOM methods like offsetWidth
const documentWidth = document.body.offsetWidth
...
},
width: documentWidth < 960 ? window.innerWidth * 0.9 : window.innerWidth * 0.6
Upvotes: 1