'Retrieving images from json server and display with relevant question
I am building a trivia app. initially I just implemented plain text Q&A trivia but now I also want to add images with questions. I am getting data from my local JSON server. I also shared one record of my JSON object at the end. Here is my API call, please help me how can retrieve images into my components. here is code sandbox link. I have included the db.json file for reference but actually, I have a JSON server.
API.ts
import { shuffleArray } from "./utils"
export type Question = {
category: string
correct_answer: string
difficulty: string
incorrect_answers: string[]
question: string
type: string
}
export type QuestionsState = Question & { answers: string[] }
export enum Difficulty {
EASY = "easy",
MEDIUM = "medium",
HARD = "hard",
}
export const fetchQuizQuestions = async (amount: number, difficulty: Difficulty): Promise<QuestionsState[]> => {
const endpoint = `http://localhost:3000/results`;
const data = await (await fetch(endpoint)).json();
console.log('**********', data)
return data.map((question: Question) => ({
...question,
answers: shuffleArray([...question.incorrect_answers, question.correct_answer]),
}))
};
and QuestionCard.jsx
type Props = {
question: string;
answers: string[];
callback: (e: React.MouseEvent<HTMLButtonElement>) => void;
userAnswer: AnswerObject | undefined;
questionNr: number;
totalQuestions: number;
}
export const QuestionCard: React.FC<Props> = ({ question, answers, callback, userAnswer, questionNr, totalQuestions }) => {
return (
<div>
<p className='number'>
Question: {questionNr} / {totalQuestions}
</p>
<p dangerouslySetInnerHTML={{ __html: question }} />
<div>
{answers.map(answer => (
<div >
<button disabled={userAnswer ? true : false} value={answer} onClick={callback}>
<span dangerouslySetInnerHTML={{ __html: answer }} />
</button>
</div>
))}
</div>
</div>
)
}
db.json few records are
{
"category": "driving",
"type": "multiple",
"difficulty": "hard",
"question": "what is the shape of give-way sign?",
"image-url": "https://cdn-01.media-brady.com/store/stnl/media/catalog/product/d/m/dmeu_y4142995_01_std.lang.all.gif",
"correct_answer": "triangle",
"incorrect_answers": [
"rounded",
"oval",
"rectengle"
]
},
Solution 1:[1]
You already have image-url in your api response so you can get it with new props like questionImage or you can convert your question props type to object and you can get from there. Then you just need to put in src of img
export const QuestionCard: React.FC<Props> = ({ question, answers, callback, userAnswer, questionNr, totalQuestions, questionImage }) => {
return (
<div>
<p className='number'>
Question: {questionNr} / {totalQuestions}
</p>
<p dangerouslySetInnerHTML={{ __html: question}} />
<img src={quesionImage} alt={"questionImage"}/>
<div>
{answers.map(answer => (
<div >
<button disabled={userAnswer ? true : false} value={answer} onClick={callback}>
<span dangerouslySetInnerHTML={{ __html: answer }} />
</button>
</div>
))}
</div>
</div>
)
}
Solution 2:[2]
I hope this solution will work for you. first add imageUrl:string
export type Question = {
category: string
correct_answer: string
difficulty: string
incorrect_answers: string[]
question: string
imageUrl: string
type: string
}
then add qImage as I did
type Props = {
question: string;
qImage?: string;
answers: string[];
callback: (e: React.MouseEvent<HTMLButtonElement>) => void;
userAnswer: AnswerObject | undefined;
questionNr: number;
totalQuestions: number;
}
export const QuestionCard: React.FC<Props> = ({
question,
qImage,
answers,
callback,
userAnswer,
questionNr,
totalQuestions }) => {
return (
<div>
<p className='number'>
Question: {questionNr} / {totalQuestions}
</p>
<img src={qImage} alt="icons" />
<p dangerouslySetInnerHTML={{ __html: question }} />
<div>
{answers.map(answer => (
<div >
<button disabled={userAnswer ? true : false} value={answer} onClick={callback}>
<span dangerouslySetInnerHTML={{ __html: answer }} />
</button>
</div>
))}
</div>
</div>
)
}
and finally use qIamge in your app like this
{!loading && !gameOver && (
<QuestionCard
question={questions[number].question}
qImage={questions[number].imageUrl}
answers={questions[number].answers}
callback={CheckAnswer}
userAnswer={userAnswers ? userAnswers[number] : undefined}
questionNr={number + 1}
totalQuestions={TOTAL_QUESTION}
/>
)}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Evren |
| Solution 2 | Anees Ahmad |
