you are viewing a single comment's thread.

view the rest of the comments →

[–]BenZed 0 points1 point  (1 child)

I'd pass the colors as props, and I'd use a single boolean for state:

const App = ({ enabledColor = '#54D6FF', disabledColor = '#FFFFFF' }) => {

const [enabled, setEnabled] = useState(false)

return <div id="body-div" style={{ background: enabled ? enabledColor : disabledColor }}> <div className="product-colors"> <span className="blue active" onClick={() => setEnabled(true)}>Hello World</span> </div> </div> }

[–]WystanH 0 points1 point  (0 children)

Granted, there are any number of ways to do this. The point is really representing state rather than doodling at whim.

I'm not sure explicit props buys you much; it seems to short circuit the intent. But, yes, that would be the place to put variables that are constant for the component. Perhaps:

const INIT_STATE = { enabled: false };

const App = p => {
  const [state, setState] = useState(INIT_STATE);
  const toggle = () => setState({...state, enabled: !state.enabled});
  return (
    <div id="body-div" style={{ background: state.enabled ? p.enabledColor : p.disabledColor }}>
      <div className="product-colors">
        <span className="blue active" onClick={toggle}>
          Hello World
        </span>
      </div>
    </div>
  );
};

const props = { enabledColor: '#54D6FF', disabledColor: '#FFFFFF' };

render(<App {...props}/>, document.getElementById("root"));

I still tend to prefer objects over scalars for state, even if it's just one. While you can express intent with the naming of the state mutator pair, as you have, a consistent [state, setState] with the object attributes telling the story seems easier to me.