Home > front end >  How to add css propety only variable is. true ? React
How to add css propety only variable is. true ? React

Time:03-09

I want to add css property if value is true. Example ->

  menuList: (styles, { selectProps }) => ({
    ...styles,
    padding: 0,
    borderRadius: 3,
    maxHeight: selectProps.setShortHeightDropDown && "120px"
  }),

And this is work. Also i am try with

  menuList: (styles, { selectProps }) => ({
    ...styles,
    padding: 0,
    borderRadius: 3,
    maxHeight: selectProps.setShortHeightDropDown ? "120px" : "
  }),

But in every time maxHeight proerty is setted.

What I need ?

If selectProps.setShortHeightDropDown === true set maxHeigh

If selectProps.setShortHeightDropDown === false not set maxHeigh

What i am try

  menuList: (styles, { selectProps }) => ({
    ...styles,
    padding: 0,
    borderRadius: 3,
    selectProps.setShortHeightDropDown ? maxHeight: selectProps.setShortHeightDropDown 
   "120px" : '
  }),

But this is can't be written.

CodePudding user response:

You can create another object.

const dynamicStyles = {};
if(selectProps.setShortHeightDropDown) {
  dynamicStyles.maxHeight = "120px";
}
// maybe some more if statements for some other dynamic props

Then add it to the original object:

menuList: (styles, { selectProps }) => ({
  ...styles,
  padding: 0,
  borderRadius: 3,
  ...dynamicStyles
}),

CodePudding user response:

Approach 1 - Template Literal

I'd recommend putting the conditional CSS properties into a class and then adding/removing this class from the target element based on your value:

e.g.

styles.css (or wherever your styles are)

.dynamic-styles {
    // Styles go here
}

app.js (or wherever your component is)

import './styles.css'; // Don't forget to import your stylesheet

function YourComponent(props) {
    ...
    const value = // Compute from props, state or otherwise
    ...
    return (
        <div className={`basic-class ${value ? 'dynamic-styles' : ''}`.trim()}>
            ...
        </div>
    );

}

Approach 2 - Computed ClassList

In more complex scenarios where you have multiple different dynamic classes, you could abstract this into a memoised value using useMemo and a classList (DOMTokenList):

    ...
    const className = useMemo(() => {
        const classList = new DOMTokenList();
        classList.add('basic-class');

        if (value === 'value-a') classList.add('dynamic-class-a')
        else if (value === 'value-a') classList.add('dynamic-class-b')

        return classList.toString();
    }, [value]);
    
    return (
        <div className={className}>
    ...

The use of useMemo here ensures the className is only computed when the dependent values change. Read more about it on the React docs.

  • Related