Home > OS >  How do you use props to reduce code of many checkboxes ReactJS
How do you use props to reduce code of many checkboxes ReactJS

Time:05-01

Just wondering how to create one function that can account for all the other colors as well, without duplicating the below functions for each color.

const blackSwitch = () => {
    if (black == true) { setBlack(false) } else { setBlack(true) }
  }
const whiteSwitch = () => {
    if (white == true) { setWhite(false) } else { setWhite(true) }
  }


<div>
                                <input
                                  type="checkbox"
                                  value="false"
                                  name="checkbox"
                                  onClick={whiteSwitch}
                                  /> White
                                <input
                                  type="checkbox"
                                  value="false"
                                  name="checkbox"
                                  onClick={blackSwitch}
                                  /> Black
</div>

CodePudding user response:

Create a function that takes an array as a parameter (array of objects). Then do forEach.

const setColor = (setColorFn, color) => setColorFn(!color)

const colors = [
  {vale: black, fn: (color) => setColor(setBlack, black)},
  {vale: white, fn: (color) => setColor(setWhite, black)}
]

colors.forEach(({value, fn}) => {
  fn(value)
})

Or if you need functions, that can be used in the code you can use reduce method.

// object should have name key right now.
const colors = [
  {vale: black, fn: (color) => setColor(setBlack, black), name: 'Black'},
  {vale: white, fn: (color) => setColor(setWhite, black), name: 'White'}
]

const colorSetters = colors.reduce((acc, next) => {
    return {...acc, [`set${next.name}`]: next.fn}
}, {})

and you can use it like this:

colorSetters.setBlack(black)

Here you have jsFiddle, which logs out the final object with color setters: https://jsfiddle.net/8angt5fj/4/

CodePudding user response:

I also found I could do this with input values, I'm just UNSURE of how to remove duplicates of a Color in case the CHECKBOX is unclicked or clicked again

const TestArrayPush = (e) => {
     setColorArray(oldArray => [...oldArray, e])
     console.log(colorArray)
 }

<input
                                  type="checkbox"
                                  value="White"
                                  name="checkbox"
                                  onClick={(e) => TestArrayPush(e.target.value)}
                                  /> White
                                <input
                                  type="checkbox"
                                  value="Black"
                                  name="checkbox"
                                  onClick={(e) => TestArrayPush(e.target.value)}
                                  /> Black
  • Related