0

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.

1

2 Answers 2

0

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
}),
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.