Home > Software engineering >  Is there a way to set multiple ternary statements in an inline style?
Is there a way to set multiple ternary statements in an inline style?

Time:10-22

I want to check for multiple states in my inline style but only the second statement is going through.

<div
  className='infoBox'
  style={
    (day ? null : { backgroundColor: 'red', color: 'white' },
    info ? null : { opacity: '0', height: '0', width: '0', marginBottom: '0' })
  }
></div>;

CodePudding user response:

I would give this a shot:

const YourComponent = () => {
  const [day, setDay] = useState(false);
  const [info, setInfo] = useState(false);

  const dayStyles = {};
  const infoStyles = {};

  if (!day) {
    dayStyles.backgroundColor = 'red';
    dayStyles.color = 'white';
  }

  if (!info) {
    infoStyles.opacity = 0;
    infoStyles.height = 0;
    infoStyles.width = 0;
    infoStyles.marginBottom = 0;
  }

  return (
    <div className='infoBox' style={{ ...dayStyles, ...infoStyles }}></div>
  );
};

export default YourComponent;

CodePudding user response:

You could try Object.assign, something like:

<div
  style={Object.assign(
    day  ? {} : { backgroundColor: 'red', color: 'white' },
    info ? {} : { opacity: '0', height: '0', width: '0', marginBottom: '0' },
  )}
>Foo</div>
  • Related