Search code examples
javascriptreactjscomponentsjavascript-objects

How to change color when condition is true


I want to change the color of the 'left--innerTopBox' whenever the changes. I believe im missing a handleChange function and an onChange.

import "./App.css";
import { useState } from "react";

function App() {
  const [color, setColor] = useState({
    color1: "#fff",
  });
  return (
    <>
      <div className="box--control">
        <div className="big--leftBox">
          left box
          <div className="left--innerTopBox" value={color.color1}>
            color here
          </div>
          <div className="left--innerBottomBox">code here</div>
        </div>

        <div className="big--rightBox">
          right box
          <div className="inputs">
            Color 1
            <input
              type="color"
              style={{ marginLeft: 10 }}
              value={color.color1}
            />
          </div>
          <div className="inputs">
            Color 2<input type="color" style={{ marginLeft: 10 }} />
          </div>
        </div>
      </div>
    </>
  );
}
export default App;

Solution

  • Try something like this:

    import "./App.css";
    import { useState} from "react";
    
    function App() {
      const [color, setColor] = useState({
        color1: "#fff",
      });
    
      const handleChange = (e) => {
        setColor({ ...color, color1:  e.target.value });
      };
    
      return (
        <>
          <div className="box--control">
            <div className="big--leftBox">
              left box
              <div
                className="left--innerTopBox"
                style={{ backgroundColor: color.color1 }}
              >
                color here
              </div>
              <div className="left--innerBottomBox">code here</div>
            </div>
    
            <div className="big--rightBox">
              right box
              <div className="inputs">
                Color 1
                <input
                  type="color"
                  style={{ marginLeft: 10 }}
                  value={color.color1}
                  onChange={handleChange}
                />
              </div>
              <div className="inputs">
                Color 2<input type="color" style={{ marginLeft: 10 }} />
              </div>
            </div>
          </div>
        </>
      );
    }
    
    export default App;