Dynamic Quiz Card Component with React, TypeScript, and Tailwind CSS
In modern web applications, creating interactive and user-friendly components is essential. One such component is the quiz card.
In this article, I'll walk you through building a dynamic quiz card component using React, TypeScript, and Tailwind CSS. This code will cover the main features, including a responsive design, interactive elements, and a countdown timer.
Key Features of the Quiz Card
Our quiz card component includes 5 important features:
- The "Next" button is disabled until an answer is selected.
- Displaying the current question number and the total number of questions.
- A countdown timer to enhance the quiz experience.
- Selected answers are highlighted for better user interaction.
- Wrote a util function
addLeadingZero
to add a leading zero if number is less than 10
This quiz card is built with Typescript and Tailwind CSS, using the best React practices.
Important Points
Here are 4 key implementation details to make our quiz card component modular and efficient:
- Reusable Quiz Option Component: Extracted the quiz option logic into a reusable component for better maintainability.
- Separation of Data: Used a separate file to manage quiz questions data.
- Icon Library: Integrated a third-party icon library for the timer icon to save development time. You can use icon of your choice.
- Consistent Theming: Applied consistent background and text colors in body to maintain a theme.
1body { 2 @apply bg-[#0f172a] text-white; 3 font-family: 'Anek Malayalam', sans-serif; 4}
Quiz Card UI
This is how Quiz Card component UI looks like:
Tailwind Quiz Card Component Code
Which function is used to serialize an object into a JSON string in Javascript?
Quiz Timer Logic
The quiz component includes a countdown timer to keep track of time.
Here’s how to set it up:
- Declare
state
for timer and set initails value to60
(seconds) - In the
useEffect
hook, we wrote the logic for counting down the time.
1const [timer, setTimer] = useState(60) 2 3useEffect(() => { 4 if (timer > 0) { 5 const countdown = setInterval(() => setTimer(timer - 1), 1000) 6 return () => clearInterval(countdown) 7 } 8}, [timer])
Quiz App Template
If you are looking for a free quiz app template built with React and Tailwind CSS, here you go!
Feel free to use this Quiz Card component in your projects.