Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally inline style a react component based on prop

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>
  );
}
like image 328
Veronica Avatar asked Mar 05 '26 00:03

Veronica


1 Answers

Fixed a typo - { before className

and you can return an empty object if selected is false else the expected value

Example:

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} : {} }}>
        {rightLabel}
      </div>
    </div>
  );
}
like image 67
Ajay Narain Mathur Avatar answered Mar 06 '26 14:03

Ajay Narain Mathur