JCastillo
JCastillo

Reputation: 336

Conditional (ternary) operator

I have a button that will generate a random color and will set the color state with that color value.

That color state will then be used to set the background color of the div.

Inside the div a have lock/unlock button that will set locked state to true/false;

Now that part I'm having trouble with is using a tenerary operator inside the style element:

what I want it to do is :

if unlock: change color

if lock: dont change color and keep the same one

import React, { Fragment, useEffect, useState } from "react";

export default function Pallete({ changeColor }) {
const [locked, setLocked] = useState(false)
  const [color, setColor] = useState(
    "#" + (((1 << 24) * Math.random()) | 0).toString(16)
  );

  useEffect(() => {
    const randomColor = "#" + (((1 << 24) * Math.random()) | 0).toString(16);
    setColor(randomColor);
  }, [changeColor]);


const lockButton = () =>{
  setLocked(!locked)
}

  return (
    <Fragment>
      <div
        ***style={{ backgroundColor: !locked? color: color }}***
        className="w-100 d-flex flex-column align-items-center justify-content-center"
      >
        <h1>#FF00FF</h1>
        <button className="btn btn-dark" onClick={lockButton}>UNLOCK</button>
      </div>
    </Fragment>
  );
}

Upvotes: 1

Views: 607

Answers (3)

Alireza HI
Alireza HI

Reputation: 1933

I change two part of your code:

useEffect(() => {
    if(locked){ // check if its locked or not
      const randomColor = "#" + (((1 << 24) * Math.random()) | 0).toString(16);
      setColor(randomColor);
    }
}, [changeColor, locked]); // add locked to watch for

You can remove the !locked ? color : color part too:

style={{ backgroundColor: color }}

Upvotes: 3

mosmk
mosmk

Reputation: 413

From what I understand this is the solution:

    useEffect(() => {

            if (!locked) {
               const randomColor = "#" + (((1 << 24) * Math.random()) | 0).toString(16);
               setColor(randomColor);
            }
            }, [changeColor, locked]);

and then in the style object set the background to color without ternary operators.

Upvotes: 2

Kevin Gilbert
Kevin Gilbert

Reputation: 1022

Option 1 ) just like you said ... have you tried ?

<Component style={{background: locked ? '#f00' : 'f0f'}} />

Option 2 ) before the Return statement, define the style.

const style = foo ? '...' : '...'
<Component style={style} />

Upvotes: 1

Related Questions