Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is string comparison the right way to do dynamic styling for variants in React-JSS?

Tags:

reactjs

jss

I have a Sandbox here:

https://codesandbox.io/s/p2wy9pp8lx

I have some dynamic styling like this:

const styles = {
  fooDisplay: props => ({
    display: props.variant === "foo" ? "block" : "none"
  }),
}

For a class like:

const Something = ({ classes, children, variant }) => {
  return (
    <div className={classes.someThing}>
      <div> variant is : {variant}</div>
      <div className={classes.fooDisplay}>I only display if variant is foo</div>
    </div>
  );
};

This does what I want.

Is using string comparison the right way to achieve this though? Or would this be bad for performance?

like image 454
dwjohnston Avatar asked Dec 07 '25 04:12

dwjohnston


1 Answers

Best practice in my opinion is to export variant constants on each element that you can reference whenever you import the element, an example would look like:

<Button variant={Button.Variant.PRIMARY}> This is a primary button </Button>

And on Button you can do a check using the same constants this.props.variant === Variant.Primary

There's no real performance issue with string comparison, it's just a weakly typed way of getting to the same solution, and looks a little bit messier. This method means there's no room for error and it's very clear what the intent is.

If you need a bit more code to understand what I mean let me know

like image 78
Tom Rowe Avatar answered Dec 12 '25 04:12

Tom Rowe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!