Dynamic CSS in typescript - How to access parameter passed to the `useStyles` method

1.6k Views Asked by At

I'm trying to access the state of my component in the useStyles method created using the react-jss package. The code seems to be correct for javascript but not for typescript according to what I found online.


import { createUseStyles } from 'react-jss';

const useStyles = createUseStyles({
  myClass: {
    height: `${height}px`, // <== squiggly line here since I don't know how to pass the parameters
  },
});

export function Collapse() {

  const [height, setHeight] = useState(18);
  const classes = useStyles(height);

  return (
    <div>...</div>
  );
}

How can I achieve this?

2

There are 2 best solutions below

0
On BEST ANSWER

Using a function in my styles allows me to access the desired parameter.


import { createUseStyles } from 'react-jss';

const useStyles = createUseStyles({
  myClass: props => ({
    height: `${height}px`,
  }),
});

export function Collapse() {

  const [height, setHeight] = useState(18);
  const classes = useStyles({height: height});

  return (
    <div>...</div>
  );
}
0
On

it is better to make types clear when you are using jss and typescript together. in this case you need to specify type of parameters you want to pass them to jss. (read this article for better understanding)

in v10.6.0 of jss they added a feature to specify types of parameters you pass them to jss in a more handy way. in your case, first of all we specify classNames and types precisely:

import { Classes, Styles } from "jss";
import { createUseStyles } from "react-jss";

type CollapseStyleProps = { height?: number };
type CollapseClassNames = "myClass";
type CollapseClasses = Classes<CollapseClassNames>;
type CollapseStyles = Styles<CollapseClassNames, CollapseStyleProps>; //we specify types of props here

and then we will write styles in jss:

const getStyles: CollapseStyles = {
  myClass: {
    height: ({ height }) => height,
    transition: "500ms"
  }
};

const useCollapseStyle: (data?: any) => CollapseClasses = createUseStyles(getStyles);

now in the last step, start implementing Collapse component itself:

function Collapse() {
  const [height, setHeight] = useState(18);
  const classes = useCollapseStyle({ height });

  const heightHandler = () => {
    height === 18 ? setHeight(108) : setHeight(18);
  };

  return (
    <div>
      <div className={classes.myClass}>Test App</div>
      <button onClick={heightHandler}>toggle height</button>
    </div>
  );
}

you can see working example here on codesandbox