Git Product home page Git Product logo

react-quiz-component's Introduction

react-quiz-component

📙 React Quiz Component NPM version License Total NPM Download

react-quiz-component is a ReactJS component allowing users to attempt a quiz.

Features

  • JSON-based input
  • Quiz landing page showing title, synopsis and number of questions
  • Quiz Input Validator
  • Multiple answers with single correct answer
  • Multiple answers with multiple correct answers
  • Support text and photo answers
  • Continue till answered correctly
  • Show explainations when answered correctly or not
  • Quiz result page at the end with the dropdown filtering all questions or only those you answered correctly or incorrectly
  • Support custom result page
  • Return quiz summary at the page
  • Allow Instant feedback
  • Allow retry until the answer is selected correctly
  • Allow markdown in Question
  • Allow Picture in Question
  • Scoring System
  • Shuffling Questions / Answers
  • Timer Support
  • Support Pause/Resume Timer
  • Shows unanswered questions

Installing

npm i react-quiz-component

Importing react-quiz-component

import Quiz from 'react-quiz-component';

Defining Your Quiz Source

The quiz source is a JSON object. You can use react-quiz-form to generate it.

export const quiz =  {
  "quizTitle": "React Quiz Component Demo",
  "quizSynopsis": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim",
  "nrOfQuestions": "4",
  "questions": [
    {
      "question": "How can you access the state of a component from inside of a member function?",
      "questionType": "text",
      "questionPic": "https://dummyimage.com/600x400/000/fff&text=X", // if you need to display Picture in Question
      "answerSelectionType": "single",
      "answers": [
        "this.getState()",
        "this.prototype.stateValue",
        "this.state",
        "this.values"
      ],
      "correctAnswer": "3",
      "messageForCorrectAnswer": "Correct answer. Good job.",
      "messageForIncorrectAnswer": "Incorrect answer. Please try again.",
      "explanation": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
      "point": "20"
    },
    {
      "question": "ReactJS is developed by _____?",
      "questionType": "text",
      "answerSelectionType": "single",
      "answers": [
        "Google Engineers",
        "Facebook Engineers"
      ],
      "correctAnswer": "2",
      "messageForCorrectAnswer": "Correct answer. Good job.",
      "messageForIncorrectAnswer": "Incorrect answer. Please try again.",
      "explanation": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
      "point": "20"
    },
    {
      "question": "ReactJS is an MVC based framework?",
      "questionType": "text",
      "answerSelectionType": "single",
      "answers": [
        "True",
        "False"
      ],
      "correctAnswer": "2",
      "messageForCorrectAnswer": "Correct answer. Good job.",
      "messageForIncorrectAnswer": "Incorrect answer. Please try again.",
      "explanation": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
      "point": "10"
    },
    {
      "question": "Which of the following concepts is/are key to ReactJS?",
      "questionType": "text",
      "answerSelectionType": "single",
      "answers": [
        "Component-oriented design",
        "Event delegation model",
        "Both of the above",
      ],
      "correctAnswer": "3",
      "messageForCorrectAnswer": "Correct answer. Good job.",
      "messageForIncorrectAnswer": "Incorrect answer. Please try again.",
      "explanation": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
      "point": "30"
    },
    {
      "question": "Lorem ipsum dolor sit amet, consectetur adipiscing elit,",
      "questionType": "photo",
      "answerSelectionType": "single",
      "answers": [
        "https://dummyimage.com/600x400/000/fff&text=A",
        "https://dummyimage.com/600x400/000/fff&text=B",
        "https://dummyimage.com/600x400/000/fff&text=C",
        "https://dummyimage.com/600x400/000/fff&text=D"
      ],
      "correctAnswer": "1",
      "messageForCorrectAnswer": "Correct answer. Good job.",
      "messageForIncorrectAnswer": "Incorrect answer. Please try again.",
      "explanation": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
      "point": "20"
    },
    {
      "question": "What are the advantages of React JS?",
      "questionType": "text",
      "answerSelectionType": "multiple",
      "answers": [
        "React can be used on client and as well as server side too",
        "Using React increases readability and makes maintainability easier. Component, Data patterns improves readability and thus makes it easier for manitaining larger apps",
        "React components have lifecycle events that fall into State/Property Updates",
        "React can be used with any other framework (Backbone.js, Angular.js) as it is only a view layer"
      ],
      "correctAnswer": [1, 2, 4],
      "messageForCorrectAnswer": "Correct answer. Good job.",
      "messageForIncorrectAnswer": "Incorrect answer. Please try again.",
      "explanation": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
      "point": "20"
    },
  ]
} 

Locale Customization

If you want to use your customized text, you can add appLocale into your quiz source. Below is the default one. and will be replaced dynamically.

"appLocale": {
  "landingHeaderText": "<questionLength> Questions",
  "question": "Question",
  "startQuizBtn": "Start Quiz",
  "resultFilterAll": "All",
  "resultFilterCorrect": "Correct",
  "resultFilterIncorrect": "Incorrect",
  "prevQuestionBtn": "Prev",
  "nextQuestionBtn": "Next",
  "resultPageHeaderText": "You have completed the quiz. You got <correctIndexLength> out of <questionLength> questions."
} 

Passing to Quiz container

import { quiz } from './quiz';
...
<Quiz quiz={quiz}/>

Shuffling Question Set

import { quiz } from './quiz';
...
<Quiz quiz={quiz} shuffle={true}/>

Shuffling Answer Set

import { quiz } from './quiz';
...
<Quiz quiz={quiz} shuffleAnswer={true}/>

Disabling Default Result Page

import { quiz } from './quiz';
...
<Quiz quiz={quiz} showDefaultResult={false}/>

Enabling Custom Result Page

  • In order to enable custom result page, showDefaultResult has to be false.
import { quiz } from './quiz';
...
const renderCustomResultPage = (obj) => {
  console.log(obj);
  return (
    <div>
      This is a custom result page. You can use obj to render your custom result page
    </div>
  )
}
```

Enabling onComplete Action

import { quiz } from './quiz';
...
const setQuizResult = (obj) => {
  console.log(obj);
  // YOUR LOGIC GOES HERE
}
...
<Quiz quiz={quiz} showDefaultResult={false} onComplete={setQuizResult}/>

Example of Quiz Summary returned to customResultPage and onComplete

Object
  numberOfCorrectAnswers: 4
  numberOfIncorrectAnswers: 1
  numberOfQuestions: 5
  questions: Array(5)
    0: {question: "Which of the following concepts is/are key to ReactJS?", questionType: "text", answers: Array(3), correctAnswer: "3", messageForCorrectAnswer: "Correct answer. Good job.", …}
    1: {question: "ReactJS is developed by _____?", questionType: "text", answers: Array(2), correctAnswer: "2", messageForCorrectAnswer: "Correct answer. Good job.", …}
    2: {question: "How can you access the state of a component from inside of a member function?", questionType: "text", answers: Array(4), correctAnswer: "3", messageForCorrectAnswer: "Correct answer. Good job.", …}
    3: {question: "Lorem ipsum dolor sit amet, consectetur adipiscing elit,", questionType: "photo", answers: Array(4), correctAnswer: "1", messageForCorrectAnswer: "Correct answer. Good job.", …}
    4: {question: "ReactJS is an MVC based framework?", questionType: "text", answers: Array(2), correctAnswer: "2", messageForCorrectAnswer: "Correct answer. Good job.", …}
  userInput: (5) [1, 2, 1, 2, 3]
  totalPoints: 100
  correctPoints: 40

Showing Instant Feedback

import { quiz } from './quiz';
...
<Quiz quiz={quiz} showInstantFeedback={true}/>

Answering the same question till it is correct

import { quiz } from './quiz';
...
<Quiz quiz={quiz} continueTillCorrect={true}/>

Timer Feature

import { quiz } from './quiz';
...
<Quiz quiz={quiz} timer={60}/>

Pause / Resume Timer Feature

import { quiz } from './quiz';
...
<Quiz quiz={quiz} timer={60} allowPauseTimer={true}/>

Props

Name Type Default Required Description
quiz object null Y Quiz Json Object
shuffle boolean false N Shuffle the questions
shuffleAnswer boolean false N Shuffle the answers
showDefaultResult boolean true N Show the default result page
customResultPage function null N A quiz summary object will be returned to the function and users can use it to render its custom result page
onComplete function null N A quiz summary object will be returned to the function
showInstantFeedback boolean false N Show instant feedback when it is true
continueTillCorrect boolean false N Continue to select an answer until it is correct
onQuestionSubmit function null N A user response for a question will be returned
disableSynopsis boolean false N Disable synopsis before quiz
timer number false N Sets timer in seconds
allowPauseTimer boolean false N Pause / Resume timer

Contribution

  • Clone the repository
  • Run npm install
  • Run npm run dev
  • Run npm run lint
  • Make a PR to develop and describe the changes

Demo

The demo is available at https://wingkwong.github.io/react-quiz-component/

License

This project is licensed under the MIT License - see the LICENSE file for details

react-quiz-component's People

Contributors

aabbi15 avatar alexneo2003 avatar chyke007 avatar dependabot[bot] avatar jayeshyadav99 avatar mrinmay7875 avatar pranav514 avatar renovate[bot] avatar shariar-hasan avatar viditagrawal56 avatar vijayabaskar56 avatar vishakhasainani avatar wingkwong avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

react-quiz-component's Issues

Maximum update depth exceeded with onComplete props

Check demo - https://codesandbox.io/s/quiz-example-error-b6c81
If i want to reuse onComplete result object i useState for this but i catch error

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

  "dependencies": {
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-quiz-component": "0.3.4",
    "react-scripts": "3.4.1"
  },

image

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

npm
package.json
  • dompurify ^3.0.0
  • nanoid ^5.0.5
  • react ^18.2.0
  • react-dom ^18.2.0
  • snarkdown ^2.0.0
  • @babel/plugin-proposal-class-properties ^7.3.0
  • @babel/plugin-proposal-nullish-coalescing-operator ^7.18.6
  • @babel/plugin-proposal-object-rest-spread ^7.3.2
  • @babel/preset-env ^7.3.1
  • @babel/preset-react ^7.23.3
  • @rollup/plugin-babel ^6.0.4
  • @rollup/plugin-commonjs ^25.0.7
  • @rollup/plugin-html ^1.0.3
  • @rollup/plugin-node-resolve ^15.2.3
  • @rollup/plugin-replace ^5.0.5
  • @rollup/plugin-terser ^0.4.4
  • babel-loader ^9.1.3
  • css-loader ^7.0.0
  • css-minimizer-webpack-plugin ^6.0.0
  • eslint ^8.4.1
  • eslint-config-airbnb ^19.0.2
  • eslint-plugin-import ^2.25.3
  • eslint-plugin-jsx-a11y ^6.5.1
  • eslint-plugin-react ^7.27.1
  • eslint-plugin-react-hooks ^4.3.0
  • html-webpack-plugin 5.6.0
  • mini-css-extract-plugin ^2.7.6
  • prop-types ^15.7.2
  • rollup ^4.3.0
  • rollup-plugin-peer-deps-external ^2.2.4
  • rollup-plugin-postcss ^4.0.2
  • terser-webpack-plugin ^5.3.9
  • webpack ^5.69.1
  • webpack-cli ^4.9.2
  • webpack-dev-server ^5.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

New feature

In this library, the only problem is the question come one by one is this possible to display 10 question at the same time!!!

Display correct aswer AFTER you click Next

Instead of giving instant answer upon making a choice, it would make more sense to display the correct answer AFTER you click the Next button. That way you can a) change your mind as many times you want before "submitting" a choice/answer and b) invoke an API to check the answer if your questions are served via remote services for example.

Localization and custom Header

Hi, I suggest you could add these features:

  • Custom Header ( you can change the "X Questions" part)
  • An option for change the text variables value (like the "default" header "Questions" text

I'm thankful for your component.

Prop to disable "Continue till answered correctly"

Is there any way to take the input from the user only once? So when the user clicks on an answer (Maybe correct or incorrect), they should not be able to change the answer when this prop is set to false. (continueTillCorrect={false})

Also when this prop is set to false, we could auto click on Next button after 1-2 seconds timeout (Just additional suggestion)

When I click next button It scrolls to top

Hello there
So I have large content and when users click the following button it scrolls to the top and users need to scroll down for selecting an answer and finish the quiz. But it's uncomfortable to scroll down every time for every question. Please fix it

How to include pictures in question?

Is there a way to include pictures in questions without editing the question.jsx file in the node modules?

I can see questionPic = _questions$i.questionPic, in the quiz.js inside the node modules but the value is never read.

Reducer?

This is an amazing little component. Thanks for building this. One question I have is that you've got a ton of states in the Core. Wouldn't it be easier to maintain and debug if you used a Reducer here for all these states? Also, wouldn't it better to create some sort of Context here around the whole quiz to save some states? Thanks.

Multiple selection allows answers to be selected after clicking an incorrect answer

I noticed on the multiple selection you can continue to click on answers when you got the previous answer incorrect.

This probably isnt a bug but it would be much better if you coundnt continue to select an answer after they got one incorrect. It makes things too easy.

This would be a big feature improvement for multiple answers.

React 18

Im getting an error when trying to install it.
It seems like dont work with the latest version of React (18.0.0)

_marked.default

There is a huge type error here upon installing and using a simple <Quiz quiz={quiz} />

What to do? How to get it working?

Timer for question

I want to set a timer.For each question if the time is finished that particular question will be skipped
how to implement this feature!?

replacing "single selection" and "pick 1" displays with "Next" button

Hi - thanks (again!) for this great quiz component!

I'm trying to edit the styling a bit, but I'm having some trouble. I would like to replace the "single selection" and "pick 1" displays with the "Next" button, but I am not finding the correct place to make this change. Any advice would be greatly appreciated. So, basically, instead of having the "single selection" and "pick 1" buttons at the top, I would like them to NOT display at all, and then once the user selects the correct answer, the "Next" button will appear in the space where the "single selection" and "pick 1" buttons were originally - not at the bottom of the screen.

Here is my implementation of the quiz app so far, in case you are interested:
https://ap-theory.now.sh/pitch-quiz

Thanks again,

Jon

Shuffle variants

Hi there,
I want to shuffle variants of questions. It will be like shuffle questions but for variants

Next button navigates to top of page when clicked

Hi there
I have a large page and at the bottom, I have a quiz. when I click the next button to get the next question, it scrolls up(navigates to the top) and it's uncomfortable to scroll down every question. is there any way to fix it?

Non-selected answers aren't being disabled when question type is 'multiple'

Once the user has picked all possible answers from a multiple answer question, the non-selected answers don't get disabled. Unlike when the question type is single.
This can be observed in question four of the demo provided (https://wingkwong.github.io/react-quiz-component)

Non-selected answers is being greyed out as expected (question type: single)
Screenshot 2023-02-25 at 09 18 46

Non-selected answer isn't being greyed out (question type: multiple)
Screenshot 2023-02-25 at 09 19 07

This issue allows the user to keep selecting answers even after they've selected as many answers as they are allowed, causing this in the the results page
image

React 17

How do I get this to work with React v17 and up? Is the package not compatible with newer versions of react?

quiz duration and disable refresh

there must be a time for quiz after that quiz have to show results. and user can't refresh the page if quiz has been started. and when you start the quiz that timer starts and you have to complete that quiz in time

Disable correct answer

Is it possible to disable correct answer while choose from some answer. Instead, the answer and score display into the end of page? Thanks

Show the total number of questions

I am wondering how to show the total number of questions that need to be answered as well as the current question being answered:

1 of 5
Question 1

2 of 5
Question 2

Thanks.

No correct answer

Hi,

My quiz doesn't have a correct answer, it's a questionaire about drinking, with a question being like:
How many drinks do you drink a week?
a. none
b. less than 5
c. more than 10

When they choose one it just applies a score no a correct or incorrect answer. Is this possible?

Thanks!

qustion

hi
do u have idea for adding timer ?

revealAnswerOnSubmit not working correctly

Hey!
I want the quiz to show the right answer (as instant feedback) immediately when clicked.
i.e. if user selects any answer, the correct answer should be highlighted.

I assume that the property revealAnswerOnSubmit={true} should do this operation, but it doesn't seem to work.

Result upon clicking: nothing is highlighted at all!

Reload Quiz if doesn't pass?

What's the best way to reload the quiz component, if the user doesn't pass the quiz (based on a predefined value which determines whether they have passed or not)? We are currently using a custom result page, with a state, scorePass, that tracks whether the user passed the quiz or not. Our code is below. But, when we try to re-render the component by setting the state of another value, on an onClick, the re-render simply brings us back to the custom result page, and not to the start of the quiz. Any thoughts?

const renderCustomResultPage = (obj) => {
   function retakeQuiz(e) {
       const item = e.target.value;
       console.log(item);
       setQuizRetake(true);
      
   }
   function GetScore(props) {
           
            if (props.score) {
                return (
                    'Congratulations! You passed the test.' 
                    )
            } else {   
                return (
                    <p>We are sorry. You did not pass the test initially. 
                    <button value="retakeQuiz" onClick={retakeQuiz}>Take it Again</button>
                    </p>
                    )
            }
       
       }

   
   return (
     
      <div>
               
                       
                        <GetScore score={scorePass} />
              
               
     </div>
     
      
    
   )
 }

Can i quit a quiz and still get result summary?

Is it possible to quit a quiz and still get result summary?
For example, I want to quit a 10 questions quiz in question number 4 and still get result summary?

Also how do we include quiz timing?

Show all questions

Hi all,

how do i show all the questions and not showing them one by one. Also how to allow answer change and review all answer before submit

Allow to disable default style

I'd like to disable the default style to use my own stylesheet without having to override everything with !important.

onComplete props on Quiz component

Hi, it would be nice to pass a function as props "onComplete" to the component.

Is there any way now to understand if the quiz is ended and get results?

Thanks, Au

0.5.0 yarn install results Uncaught TypeError: (0 , _marked.marked) is not a function

Hello, thank you for your work and the lib whose features looks very nice!

After running through previous issues concerning this error ( 79 and 35 ), I'm facing this issue even tho I use 0.5.0 after a yarn install.

Fresh install, nothing fancy:

Simple component as per the readme as :

...
const quiz = {...}
...
return <Quiz quiz={quiz}/>
...

results in:
Screenshot 2022-12-08 at 15 52 50

I also tried:

yarn add react-quiz-component@https://github.com/wingkwong/react-quiz-component.git\#develop

(which seems to fail for other reasons)

Any input truly appreaciated.

Custom result rendering error

Hello,
I have an issue, when rendering the result, the explanations don't appear.
I even tried with the original example, the results appear but I can't see the explanations.
Below is an exemple of how I'm rendering the component.
If I add showDefaultResult={false} and customResultPage={renderCustomResultPage} then there is no render at all.

Also, when I add a console.log(obj) in the const renderCustomResultPage = (obj) => {}, the results are duplicated in the console.

Quiz :
<Quiz
className={myClass}
quiz={myQuiz}
shuffle={true}
showDefaultResult={false}
customResultPage={renderCustomResultPage}
/>

Any help would be welcome. Thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.