Conditionally inline style a react component based on prop

Viewed 9097

I need to set the background color of a div based on a prop passed into my react component. Inline styling of React components I am pretty clear on, but I don't know how to correctly apply the inline style to change depending on a prop. I only want to assign the value of the prop rightSideColor in the inline styling of right-toggle if the prop selected is equal true.

export default function UiToggle(props) {
  const { leftLabel, rightLabel, selected, rightSideColor, leftSideColor } = props;

  return (
    <div className="lr-toggle-select" style={{ width: `${width}px` }} >
      <div className="lr-gray-background" />
      <div>
        {leftLabel}
      </div>
      <div className={'lr-toggle right-toggle' style={{ selected ? (backgroundColor: rightSideColor) : null }}>
        {rightLabel}
      </div>
    </div>
  );
}
4 Answers

You can conditionally set the value of attributes like style, override them using rules of precedence, and determine whether to include them at all.

export default function UiToggle(props) {
  const { leftLabel, rightLabel, selected, rightSideColor, leftSideColor } = props;
  //specify style and id (and any other attributes) or don't.
  const attrs = selected ? { style: { backgroundColor: "rightSideColor" },id:"hi123" }:{}
  //Conditionally override the class names if we want:
  if (props.className) attrs.className = props.className

  return (
    <div className="lr-toggle-select" style={{ width: `${width}px` }} >
      <div className="lr-gray-background" />
      <div>
        {leftLabel}
      </div>

      {/*Use the spread operator to apply your attributes from attr*/}
      {/*Note that the 'id' set below can't be overridden by attrs whereas*/}
      {/*className will be. That's because precedence goes from right to left.*/}           
      {/*Rearrange them to get what you want.*/}
      {/*Funky comment format is to make valid JSX and also make SO formatter happy*/}          

      <div className='lr-toggle right-toggle' {...attrs} id="attrs_cant_override_this_because_its_on_the_right">
        {rightLabel}
      </div>
    </div>
  );
}

Try something like this:

   <div className='lr-toggle right-toggle' style={ selected ? {backgroundColor: rightSideColor} : '' }}>
    {rightLabel}
  </div>
Related