WDI-SEA / project-4-issues

Open an issue to receive help on project 4 issues
0 stars 0 forks source link

Toggling State using Checkboxes in React #40

Closed hectorzaragoza closed 2 years ago

hectorzaragoza commented 2 years ago

What stack are you using?

DR

What's the problem you're trying to solve?

I am trying to update my state based on whether a list of items are checked or not. If checked, include in state array, otherwise don't.

Post any code you think might be relevant (one fenced block per file)

image

If you see an error message, post it here. If you don't, what unexpected behavior are you seeing?

I can push to an array but I should also be able to take elements out of it if a box is unchecked.

What is your best guess as to the source of the problem?

I think I need a toggler function...

What things have you already tried to solve the problem?

I tried StackOverflow and also using a third party npm package...

tkolsrud commented 2 years ago

Checkboxes only return boolean values so I think you need to add a conditional into your handleCheck. I.e. onClick if true append value, if false remove value

hectorzaragoza commented 2 years ago

Checkboxes only return boolean values so I think you need to add a conditional into your handleCheck. I.e. onClick if true append value, if false remove value

But I can't use the same state for multiple checkboxes...I think I need to create a state with an array of booleans for their respective checkboxes...

tkolsrud commented 2 years ago

Ahhhh, right. Yeah or have handleCheck create an array that then is used to set state in one single step. So like instead of adding and subtracting, you could think of it as just creating a whole new array every time any of the checkboxes update?

hectorzaragoza commented 2 years ago

but that array would need to be updated based on whether the checkbox is checked or not. I am not sure how the second one would work...

tkolsrud commented 2 years ago

Off the top of my head, that every time any box is clicked it updates state for all of them. So if i were to go through and click four boxes, it would update state four times... never tried that, just thinking out loud

hectorzaragoza commented 2 years ago

I still can't figure it out...

TaylorDarneille commented 2 years ago

Hector have you reviewed the bounty hunter app? We used checkboxes there. Using a different state for each checkbox is my suggestion since it will mimic what we've done already.

hectorzaragoza commented 2 years ago

Thank you all for the help!

Here is the final solution using vanilla JS. image