React
by dreiv
HTML
<div id="app"></div>
React
function renderQuestion ({ title, answers, correct }, index) {
const [answered, setAnswered] = React.useState()
return (
<div key={index}>
<p>{title}</p>
{answers.map((answer, index) => (
<button key={index} onClick={() => setAnswered(true)}>
{answer}
</button>
))}
{answered && `Correct answer: ${answers[correct]}`}
</div>
)
}
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
questions: [
{
title: "Question-1",
answers:['a', 'b', 'c', 'd'],
correct:2
},
{
title: "Question-2",
answers:['a', 'b', 'c', 'd'],
correct:0
}
]
}
}
render() {
const { questions } = this.state
return questions.map(renderQuestion)
}
}
ReactDOM.render(<App />, document.querySelector("#app"))