Home > Net >  how do i execute multiple if/then in onClick ternary function?
how do i execute multiple if/then in onClick ternary function?

Time:10-30

trying to debug, and not sure if this structure works...

onClick={()=>{ //2. an image is clicked, and the choice is added to the choiceOrder state, and then a jsonupdate is called -- 3. in ChooseBy.js
   //onclick, add or remove the choice
   choosebyprops.setChoiceOrder( choiceOrder=>
                                    choiceOrder.includes(attrprops.attrChoice)
                                    ?
                                    (
                                    (choiceIndex = choiceOrder.findIndex(attrprops.attrChoice)),
                                    (choiceOrder.filter(list=> list!==attrprops.attrChoice)),
                                    (choosebyprops.setJsonList(jsonList=> jsonList.splice(choiceIndex) )) //removes the json data for that choice
                                    )
                                    :
                                    (
                                    ( [...choiceOrder,attrprops.attrChoice] ),
                                    (choosebyprops.setJsonList(jsonList=> [...jsonList, UpdateJson({...allprops})]))  //adds json data for that choice
                                    )
                                    )
}}

i'm basically trying to make a list of jsons, where if i click the button a filtered json is added to the list for that option, if i unclick it then it's removed.

but i just wanna know if i can have multiple statements inside that that ternary function.

CodePudding user response:

Don't try to abuse the conditional operator as a replacement for if/else - if/else will allow you to create blocks, which statements can be put into much more naturally.

It sounds like you're looking to do something like this:

choosebyprops.setChoiceOrder(choiceOrder => {
    if (choiceOrder.includes(attrprops.attrChoice)) {
        const choiceIndex = choiceOrder.findIndex(attrprops.attrChoice);
        choosebyprops.setJsonList(jsonList => jsonList.splice(choiceIndex)); // this splice sounds wrong - don't mutate in React
        return choiceOrder.filter(list => list !== attrprops.attrChoice);
    } else {
        choosebyprops.setJsonList(jsonList => [...jsonList, UpdateJson({ ...allprops })]);
        return [...choiceOrder, attrprops.attrChoice];
    }
});

CodePudding user response:

I think it's more convenient to make a separate function for each handler and use the ternary operator to choose which function to be invoked. Also, refer to this question for more explanation.

  • Related