how to change jss dynamically

Viewed 66

I know many ways to do this without JSS, but this paradigm seems to make it very difficult:

const Backdrop = () => {

  const {height, width} = useWindowSize()

  const css = makeStyles(() => createStyles({
    root : {
      backgroundColor: 'black',
      backgroundImage: 'url(/img/bg.jpg)',
      height, // this value should update when window size changes
      width,
      position:'fixed',
    }
  }))()
  
  return <div className={css.root}>

  </div>
}

Update: I copy-pasted myself into a way to make this work, but it's just too much code compared to traditional CSS

  const [_windowSize, $_windowSize] = useState({ width: window.innerWidth, height: window.innerHeight })
  const handler = () => $_windowSize({ width: window.innerWidth, height: window.innerHeight })  
  useEffect(() => {
    window.addEventListener("resize", handler)
    return () => window.removeEventListener("resize", handler)
  }, [])

  return _windowSize

}

const Backdrop = () => {

  useWindowSize()

  const css = makeStyles(() => createStyles({
    root : {
      backgroundColor: 'black',
      backgroundImage: 'url(/img/bg.jpg)',
      backgroundSize: 'cover',
      height: () => window.innerHeight,
      width: () => window.innerWidth,
      position:'fixed',
    }
  }))()

  return <div className={css.root}></div>
}


Somehow makeStyles knows of every update in the DOM. It's really unintuitive.

1 Answers

Might this suit you're need?

const { height, width } = useWindowDimensions();

const style = { 
    root : {
      backgroundColor: 'black',
      backgroundImage: 'url(/img/bg.jpg)',
      backgroundSize: 'cover',
      height: height,
      width: width,
      position:'fixed'
      }
}
return <div style={style.root}></div>

useWindowDimensions is a custom effect defined like this:

/**
 * Returns window dimensions, listening to resize event.
 *
 * Example:
 *
 * const Component = () => {
 *     const { height, width } = useWindowDimensions();
 * }
 */
export function useWindowDimensions() {
    const [windowDimensions, setWindowDimensions] = useState(
        getWindowDimensions()
    );

    useEffect(() => {
        function handleResize() {
            setWindowDimensions(getWindowDimensions());
        }

        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, []);

    return windowDimensions;
}

the effect listen to window resize and update the {width, height} state causing a clean rerendering.

Related