Home > OS >  React - Randomize List Order
React - Randomize List Order

Time:04-19

I have a react function with a ul-element and 4 Listitems. I want to randomize the order of the list items, but I cant think about the easiest way.

export default function Card({ question, answer, incorrect, headlinecount }) {

  return (
    <CardStyle>
      <article>
        <h2>Question {headlinecount}</h2>
        <p>{question}</p>
      </article>
      <ChoiceStyle>
        <li>{incorrect[0]}</li>
        <li>{answer}</li>
        <li>{incorrect[1]}</li>
        <li>{incorrect[2]}</li>
      </ChoiceStyle>
      <ButtonDiv>
        <button type="button">Show Answer</button>
        <p>{answer}</p>
      </ButtonDiv>
    </CardStyle>
  );
}

CodePudding user response:

Maybe instead of creating a separate variable for answer and incorrect, you could create a single array called answers with objects like this:

[{
  answer: "foo",
  correct: false
},
{
  answer: "foo2",
  correct: true
},
// More answers
]

etc.

Then, display items from this array randomly and check the correct parameter to see if the user chose the right answer. Added bonus: this can also work with multiple correct answers.

Good luck!

CodePudding user response:

There many ways to randomise items within specific collection, but definitely the very first thing you need to do - is to create and array (collection) of elements to render:

const choices = [
  { label: "Choice 1", value: 1 },
  { label: "Choice 2", value: 2 },
  ...
  // you can get this data dynamically from any data source
];

And then map this data in your component:



export default function Card({ question, answer, incorrect, headlinecount }) {
  const renderChoice = ({ label }) => (
    <li>{label}</li>
  );

  return (
    <CardStyle>
      <article>
        <h2>Question {headlinecount}</h2>
        <p>{question}</p>
      </article>
      <ChoiceStyle>
        {choices.map(renderChoice)}
      </ChoiceStyle>
      <ButtonDiv>
        <button type="button">Show Answer</button>
        <p>{answer}</p>
      </ButtonDiv>
    </CardStyle>
  );
}

With that structure you are now able to shuffle your collection any time you init your component. You can become familiar with possible shuffling solutions from that question: How to randomize (shuffle) a JavaScript array?

Note: you may need to memoize your component or shuffled results since any component re-render may produce change of the choices order.

  • Related