style={window.innerWidth<='750 px' ?{myStyle}:{}}
can anyone help me in this?
I want to set the style according to window width.
myStyle
is a state.
CodePudding user response:
Hey here is a hook I wrote awhile back for getting the window dimensions then you can just use the width from the hook in your style tag with a ternary operator to display different styles
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height,
};
}
/**
* @returns {object} {width, height}
*/
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(
getWindowDimensions()
);
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return windowDimensions;
}
usage
const Component = () => {
const {width, height} = useWindowDimensions()
return <div style ={width > 750 ? {Place >750 styles here} : {Place < 750 styles here} }></div>
}
CodePudding user response:
The best way to do that is using a custom hook. This hook can get the current window width
and height
when the window size is changed.
The event listener is registered when the component is mounted to update the state and safely removed when it is unmounted.
import { useState, useEffect } from "react";
// hook to get window size dynamically
const useWindowSize = () => {
// Initialize state with undefined width/height so server and client renders match
// Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined
});
useEffect(() => {
// only execute all the code below in client side
if (typeof window !== "undefined") {
// Handler to call on window resize
function handleResize() {
// Set window width/height to state
setWindowSize({
width: window.innerWidth,
height: window.innerHeight
});
}
// Add event listener
window.addEventListener("resize", handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
// Remove event listener on cleanup
return () => window.removeEventListener("resize", handleResize);
}
}, []); // Empty array ensures that effect is only run on mount
return windowSize;
};
export default useWindowSize;
This solution works perfectly with server rendering as well. Import the useWindowSize
hook into the component you want and use the size as you want.
import useWindowSize from '/path/to/hooks/useWindowSize'
const MyComp = () => {
const size = useWindowSize();
return <div style={style={size.width<='750 px' ?{myStyle}:{}}}></div>;
};
export default MyComp;