Bonzo
Bonzo

Reputation: 443

Add conditional CSS property in React

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.

Upvotes: 1

Views: 710

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075635

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).

Upvotes: 4

Related Questions