i'm using Animate css in my project, and i have a form where a user should provide an answer to a question. If an answer is correct word correct
should be faded in and wrong
in opposite case. Here is a working simplified example of my code.
Stateful component:
import React, { Component } from 'react'
import FormCheckIfCorrect from './FormCheckIfCorrect'
class Form extends Component {
constructor(props) {
super(props)
this.state = {
correct: '5',
userInput: '',
userAnswer: ''
}
}
handleChange = (e) => {
this.setState({ userInput: e.target.value })
}
handleSubmit = (e) => {
e.preventDefault();
this.setState({ userAnswer: '' }, () => {
this.setState({ userAnswer: this.state.userInput })
})
}
render() {
return (
<div>
<p>2 + 3 = ? </p>
<form onSubmit={this.handleSubmit}>
<input type='number' value={this.state.userInput} onChange={this.handleChange} />
<button >Submit</button>
</form>
{this.state.userAnswer !== '' ? <FormCheckIfCorrect userAnswer={this.state.userAnswer} correct={this.state.correct} /> : ''}
</div>
)
}
}
export default Form
Functional component:
import React from 'react'
const FormCheckIfCorrect = (props) => {
let result = props.userAnswer === props.correct ? <p className="animated fadeIn">correct</p> : <p className="animated fadeIn">wrong</p>
return result
}
export default FormCheckIfCorrect
My question is about this part of my code :
handleSubmit = (e) => {
e.preventDefault();
this.setState({ userAnswer: '' }, () => {
this.setState({ userAnswer: this.state.userInput })
})
}
In order to achieve the fade in effect each time a user clicks Submit button i set userAnswer
to nothing, and then in callback i set it again to userInput
. It works(don't forget to include animate css), but i don't think it's a right way to do it. I'd appreciate if someone could tell me how to do it right.
You can refactor your component FormCheckIfCorrect
const FormCheckIfCorrect = ({ userAnswer, correct }) => (
<p className="animated fadeIn">
{ userAnswer === correct ? 'correct' : 'wrong' }
</p>
)
This way you don't repeat yourself by adding same p tags with duplicated class. Instead, we only change the content of the paragraph
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.