1

I want to add conditional CSS property to a div in such a way that if particular condition is true then only it will applied. Below is my code.

const Select = ({
  handleClick,
  title,
  permission,
}: SelectProps) => {
  return (
    <div
      onClick={handleClick}
      style={{
        marginTop: '16px',
        cursor: 'pointer',
        pointerEvents   <-- make this property conditional
        ${({ permission }) => permission && `pointerEvents: none;`}  <-- tried this but not working
      }}
    >
      <Title>{title}</Title>
    </div>
  );
};

export const RenderSelectBlock = () => {
  const checkUserPermission = checkUserPermission();
  return (
    <Select
     handleClick={() => setSelectType('Google')}
     title="Google"
     checkUserPermission={checkUserPermission}
    />
    <Select
     handleClick={() => setSelectType('Microsoft')}
     title="Microsoft"
     checkUserPermission={checkUserPermission}
    />
    <Select
     handleClick={() => setSelectType('Apple')}
     title="Apple"
     checkUserPermission={checkUserPermission}
    />
    <Select
     handleClick={() => setSelectType('Facebook')}
     title="Facebook"
     checkUserPermission={checkUserPermission}
    />
  )
);
};

So here in the last Select where title is Facebook, I want to disable it if the user don't have permission i.e. permission = false. Basically pointerEvents property should only be added for title= Facebook and should be set to none if permission = false.

1 Answer 1

4

You best option is to avoid style entirely and use className, then include a second class (maybe no-pointer-events) for the pointer-events you want to optionally include:

<div
    className={`main-class ${permission ? "no-pointer-events" : ""}`}

But if you want to do it with style, you could use undefined for when you don't want to specify it:

<div
    style={{
        marginTop: '16px',
        cursor: 'pointer',
        pointerEvents: permission ? "none" : undefined,
    }}

You could also define the style object before reaching this point in the code:

const style = {
    marginTop: '16px',
    cursor: 'pointer',
};
if (permission) {
    style.pointerEvents = "none";
}

Then use it:

<div
    style={style}

Sometimes you'll see people do this with multiple properties via spread syntax:

<div
    style={{
        marginTop: '16px',
        cursor: 'pointer',
        ...(permission ? {pointerEvents: "none"} : undefined),
    }}

...undefined is fine in an object literal (it doesn't add any properties).

Sign up to request clarification or add additional context in comments.

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.