Chap06 -> Reducing boilerplate code with React Hook From -> Implementing the answer form

master
Jason Zhu 2022-03-31 11:16:30 +11:00
parent 98125ab39c
commit d0bb6abf15
1 changed files with 37 additions and 1 deletions

View File

@ -1,17 +1,32 @@
/** @jsxImportSource @emotion/react */ /** @jsxImportSource @emotion/react */
import { css } from '@emotion/react'; import { css } from '@emotion/react';
import { gray3, gray6 } from './Styles'; import {
FieldContainer,
FieldLabel,
Fieldset,
FieldTextArea,
FormButtonContainer,
gray3,
gray6,
PrimaryButton,
} from './Styles';
import React from 'react'; import React from 'react';
import { useParams } from 'react-router-dom'; import { useParams } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { Page } from './Page'; import { Page } from './Page';
import { QuestionData, getQuestion } from './QuestionsData'; import { QuestionData, getQuestion } from './QuestionsData';
import { AnswerList } from './AnswerList'; import { AnswerList } from './AnswerList';
type FormData = {
content: string;
};
export const QuestionPage = () => { export const QuestionPage = () => {
const [question, setQuestion] = React.useState<QuestionData | null>(null); const [question, setQuestion] = React.useState<QuestionData | null>(null);
const { questionId } = useParams(); const { questionId } = useParams();
const { register } = useForm<FormData>();
React.useEffect(() => { React.useEffect(() => {
const doGetQuestion = async (questionId: number) => { const doGetQuestion = async (questionId: number) => {
const foundQuestion = await getQuestion(questionId); const foundQuestion = await getQuestion(questionId);
@ -63,6 +78,27 @@ export const QuestionPage = () => {
} on ${question.created.toLocaleDateString()} ${question.created.toLocaleTimeString()}`} } on ${question.created.toLocaleDateString()} ${question.created.toLocaleTimeString()}`}
</div> </div>
<AnswerList data={question.answers} /> <AnswerList data={question.answers} />
<form
css={css`
margin-top: 20px;
`}
>
<Fieldset>
<FieldContainer>
<FieldLabel htmlFor="content">Your Answer</FieldLabel>
<FieldTextArea
{...register('content')}
id="content"
name="content"
/>
</FieldContainer>
<FormButtonContainer>
<PrimaryButton type="submit">
Submit Your Answer
</PrimaryButton>
</FormButtonContainer>
</Fieldset>
</form>
</React.Fragment> </React.Fragment>
)} )}
</div> </div>