리액트로 퀴즈 만들기

Perfume·2020년 11월 8일
0

https://medium.com/@officialrajdeepsingh/create-modern-quiz-with-react-js-8902f34074db 이 글을 참조함. 그대로 번역한 것은 아니고 내 입맛대로 좀 고쳤다.

Index.js File

Index.js는 메인 파일이다. 이곳에 CSS 파일을 추가하고 컴포넌트들을 import한다. Header와 Quiz 등의 컴포넌트 뿐만 아니라 대부분의 중요한 render 메서드는 이곳에서 사용할 것이다.

quiz.scss

scss 파일을 하나 생성한다. 그리고 button, header 등에 입힐 각종 스타일은 이곳에서 설정해준다.

quizdata.json

일단 데모용으로 Mock data가 필요하다. 각 인덱스마다 {}를 만든다. object 안에는 id, quiz, FindAnswer, rightAnswer를 추가한다. 그리고 FindAnswer 안에는 사용자가 누를 수 있는 답변의 갯수만큼 값을 가진 배열을 추가한다.

예시:


let quizdata = [
{
id: 1,
quiz: "What is your coffee experience level?"
FindAnswer: ["I’m pretty new to all of this", "I’m at an intermediate stage", "I’m pretty advanced", "I’m a total coffee nerd"]
rightAnswer: "I’m pretty new to all of this"
}

]

export default quizdata;

Quiz component는 다섯 가지 스텝으로 동작한다.

step 1 :

먼저 state를 만든다. dataQuestion이라는 변수를 만들고 그 변수는 배열의 형태를 가질 것이라는 걸 알 수 있도록 값을 []로 설정한다.

step 2 :

setStateFunstion이라는 함수를 만든다. 이 함수의 안에서 setState 메서드를 사용할 것이며, quizdata가 dataQuestion 안에 set 될 수 있도록 설정한다.

step 3 :

ComponentDidMount로 setStateFunstion를 불러준다.

step 4, step 5 :

이 단계에서는 map 메서드를 사용할 것이다. map을 돌림으로써 h2 태그와 Answer component 안에 아까 만든 데이터를 넣어줄 수 있다.

Answer Component

step 1 :

Create a state with 3 parameters first Answer, second clickCheck and third rightAnaswer.

step 2 :

We use javascript ternary operator, map function with and event function to clickCheck true to get value to return a button. in this button, we call an Event function.
when some buddy clicks on the button this button function uses The setState method set false on clickCheck.
then the ternary operator runs false code to get answer data so simple.

profile
공부하는 즐거움

0개의 댓글