4

NOTE : I have changed the sandbox link to the working code with some notes to what I had before that wasn't working correctly!

I'm still wondering if the code on the bottom is redundant though.

https://codesandbox.io/embed/sharp-satoshi-pgj5f?fontsize=14&hidenavigation=1&theme=dark

Alright this time I've added a URL to a sandbox with the basic idea of what is going on.

I have a styled-components JS file with a Button that I am trying to toggle the background color for onClick by passing prop values for the color, and to have a boolean attached so that I can later add API data to display based on the true or false status.

Currently with how it is coded, the first click always prints the initial false state, instead of immediately switching to true

Also, in my original code, I have a button for DAY, WEEK, MONTH to toggle a graph showing data over those time frames if their respective button returns true:

  <ButtonContainer>     
    
    <Button onClick={onClickDay} background={buttonColorDay} color={colorDay}>Day</Button>
    <Button onClick={onClickWeek} background={buttonColorWeek} color={colorWeek}>Week</Button>
    <Button onClick={onClickMonth} background={buttonColorMonth} color={colorMonth}>Month</Button>

  </ButtonContainer>  

The top right of the image is what I'm trying to emulate: enter image description here

Each of those buttons has its own set of 3 useStates and its own onClick just like the single button in the sandbox. Is that redundant or ok?

  const [clickedDay, setClickedDay] = useState(false);
  const [clickedWeek, setClickedWeek] = useState(false);
  const [clickedMonth, setClickedMonth] = useState(false);
  const [buttonColorDay, setButtonColorDay] = useState('lightgray');
  const [buttonColorWeek, setButtonColorWeek] = useState('lightgray');
  const [buttonColorMonth, setButtonColorMonth] = useState('lightgray');
  const [colorDay, setColorDay] = useState('gray');
  const [colorWeek, setColorWeek] = useState('gray');
  const [colorMonth, setColorMonth] = useState('gray');

  const onClickDay = () => {
    ...
  }

  const onClickWeek = () => {
    ...
  }

  const onClickMonth = () => {
    ...
  }

For now, I'm not worried about having the other buttons change to false when one is changed to true, I just want the buttons to work correctly.

@__@

Matt
  • 41
  • 2

1 Answers1

0
  useEffect(() => {
    console.log(clickedDay);
  }, [clickedDay]);

All it seems it took was a useEffect...

Also printing inside of the useEffect prints the correct state, whereas printing after using a setter inside of the handler function prints the previous state it seems.

Matt
  • 41
  • 2