Search code examples
reactjsgraphqlconditional-rendering

How to change order of rendering in a React map


I have a simple task and I feel the answer to this question is also simple. But for some reason I can't wrap my head around it. I'm supposed to get a list of questions from a database and display them on the site. This particular section is yes or no questions. When I get the questions from the database, most of them are already in order, "yes" and then "no". However, there's one that's flipped. So my question is, how do I flip the reversed one to its correct order?

I honestly haven't tried much because like I said, for some reason I can't wrap my head around it. But I do know that in the database the questions have a field called order where yes is 0 and no is 1. So I'm guessing I'll have to use that in some way.

Here's my code for rendering the questions,

{state.surveyQuestions.map(question => (
    <span key={question.question.id}>
        <FormLabel className={classes.label} component="legend">{question.question.label}</FormLabel>
        <RadioGroup value={state.consent} onChange={handleChange} style={{ height: 'auto', padding: '10px' }}>
            {question.question.choices.items.map(choice => (
                <FormControlLabel key={choice.order} style={{ paddingTop: '1px' }} value={choice.value} control={<Radio />} label={choice.label} />
            ))}
        </RadioGroup>
    </span>
))}

and here's what's coming from the database,

"choices": {
    "items": [
        {
            "label": "No",
            "value": "{\"value\":\"0\"}",
            "dataUID": null,
            "description": "No",
            "order": 1,
            "goto": null
        },
        {
            "label": "Yes",
            "value": "{\"value\":\"1\"}",
            "dataUID": null,
            "description": "Yes",
            "order": 0,
            "goto": null
        }
    ]
}

Solution

  • Use Array.protoype.sort() to sort the 'choices' with a custom function;

    const data = [
        {
            "label": "No",
            "value": "{\"value\":\"0\"}",
            "dataUID": null,
            "description": "No",
            "order": 1,
            "goto": null
        },
        {
            "label": "Yes",
            "value": "{\"value\":\"1\"}",
            "dataUID": null,
            "description": "Yes",
            "order": 0,
            "goto": null
        }
    ];
    
    // Full function for readability
    function orderByOrderValue( a, b ) {
      if ( a.order < b.order ){
        return -1;
      }
      if ( a.order > b.order ){
        return 1;
      }
      return 0;
    }
    
    console.log(data.sort(orderByOrderValue));
    
    // Or use the one-liner
    // data.sort((a,b) => (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0));