Skip to content

Instantly share code, notes, and snippets.

@mathisonian
Last active March 30, 2020 23:18
Show Gist options
  • Save mathisonian/b7487c66c8b07adfb13c1b50003c9051 to your computer and use it in GitHub Desktop.
Save mathisonian/b7487c66c8b07adfb13c1b50003c9051 to your computer and use it in GitHub Desktop.
Example question component that is only shown after a previous question is answered correctly. I haven't tested this but it should provide the basic structure.
How to use:
[var name:"q1Correct" value:false /]
[Question options:`["test1", "test2"]` trueAnswer:"test1" correct:q1Correct /]
[var name:"q2Correct" value:false /]
[Question options:`["test1", "test2"]` trueAnswer:"test2" correct:q2Correct showAfter:q1Correct /]
const React = require('react');
class Question extends React.Component {
constructor(props) {
super(props);
this.state = {
showAnswer: false,
selectedAnswer: null
}
}
onChange(e) {
this.setState({
selectedAnswer: e.target.value
})
}
onButton(e) {
this.setState({
showAnswer: true
})
}
render() {
const { hasError, idyll, updateProps, ...props } = this.props;
const { selectedAnswer } = this.state;
if (props.showAfter === false) {
return null;
}
return (
<div >
{/* The radio buttons */}
{options.map(d => {
if (typeof d === 'string') {
return (
<label key={d}>
<input
type="radio"
checked={d === value}
onChange={this.onChange}
value={d}
name={this.id}
/>
{d}
</label>
);
}
return (
<label key={d.value}>
<input
type="radio"
checked={d.value === value}
onChange={this.onChange}
value={d.value}
name={this.id}
/>
{d.label || d.value}
</label>
);
})}
<button onClick={this.onButton}>
Submit
</button>
{
showAnswer && selectedAnswer === props.trueAnswer ?
<div>
You answered {selectedAnswer}. This is correct!
</div>
: null
}
{
showAnswer && selectedAnswer !== props.trueAnswer ?
<div>
You answered {selectedAnswer}. This is incorrect
</div>
: null
}
</div>
);
}
}
module.exports = Question;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment