I am new to js and React. I want to print some data from database in html page using javascript and react. I have a simple Flask app which is storing some form questions with possible answers in database. I want to print them dynamically in my React components. Is there any way to create components in loop depending on number of questions? Here is snippet of my Python code:
@app.route('/form.html')
def form():
form_data = db.get_all_questions()
return render_template("form.html", data=form_data)
Here is my form.html:
<div class="questions">
<div class="question" id="question1">
</div>
<div class="question" id="question2">
</div>
<div class="question" id="question3">
</div>
</div>
Here is my js file:
class Question extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<p>{this.props.content}</p>
<p>{this.props.id}</p>
<div className="rating_scale">
<form>
<label>
<input type="radio" name="rad" value="1" />
<span>1</span>
</label>
<label>
<input type="radio" name="rad" value="2" />
<span>2</span>
</label>
<label>
<input type="radio" name="rad" value="3" />
<span>3</span>
</label>
<label>
<input type="radio" name="rad" value="4" />
<span>4</span>
</label>
<label>
<input type="radio" name="rad" value="5" />
<span>5</span>
</label>
</form>
</div>
</div>
);
}
}
ReactDOM.render(
<Question content= "question 1" />,
document.querySelector("#question1")
);
ReactDOM.render(
<Question content= "question 2" />,
document.querySelector("#question2")
);
ReactDOM.render(
<Question content= "question 3" />,
document.querySelector("#question3")
);
In HTML I can loop throw my questions like so:
{% for question in data %}
<tr>
<td>{{ question['question_id'] }}</td>
<td>{{ question['question_text'] }}</td>
<br>
{% for AnswerId, Answer in question['possible_answers'].items()%}
<td> {{AnswerId}} : {{Answer}} </td>
<br>
{% endfor %}
</tr>
{% endfor %}
But how to get similar behavior in javascript? I just don't want to hard-code all my question divs, but creating react components which are including this div dynamically depending on number of questions. In content prop I want to display the question text.