분류
Reactjs
자신 만의 React 커스텀 훅 작성 (4)
본문
import useRequiredFields from './useRequiredFields'
function MultiStepForm() {
const [formIndex, setFormIndex] = useState(0)
const [namesFilled, updateNames] = useRequiredFields([ 'first-name', 'last-name', ]) const [socialsFilled, updateSocials] = useRequiredFields([ 'github', 'twitter', 'codepen', ])
// Advance through the multiple stages of the signup
function handleFormSubmit(event) {
event.preventDefault()
setFormIndex(formIndex + 1)
}
return (
<>
{/* First section of the form */}
{formIndex === 0 && (
<form onSubmit={handleFormSubmit} autoComplete="off">
<p>Your name</p>
<div className="input-row">
<label htmlFor="first-name">First Name</label>
<input
id="first-name"
type="text"
onChange={updateNames} />
</div>
<div className="input-row">
<label htmlFor="last-name">Last Name</label>
<input
id="last-name"
type="text"
onChange={updateNames} />
</div>
<div>
<button
type="submit"
disabled={!namesFilled} >
Continue
</button>
</div>
</form>
)}
{/* Second section of the form */}
{formIndex === 1 && (
<form onSubmit={handleFormSubmit} autoComplete="off">
<p>Your social profiles</p>
<div className="input-row">
<label htmlFor="github">Github Username</label>
<input
id="github"
type="text"
onChange={updateSocials} />
</div>
<div className="input-row">
<label htmlFor="twitter">Twitter Username</label>
<input
id="twitter"
type="text"
onChange={updateSocials} />
</div>
<div className="input-row">
<label htmlFor="codepen">Codepen Username</label>
<input
id="codepen"
type="text"
onChange={updateSocials} />
</div>
<div>
<button
type="submit"
disabled={!socialsFilled} >
Submit
</button>
</div>
</form>
)}
{/* Thank you message */}
{formIndex === 2 && (
<div>
<p>Thanks!</p>
<button type="button" onClick={() => setFormIndex(0)}>
Back to start
</button>
</div>
)}
</>
)
}
최종 고려 사항
지금까지 이해했다면 "입력 요소에 HTML5 필수 속성을 사용하고 모든 필드를 필수 필드로 만들려면 최소 / 최대 속성 만 사용하십시오"라고 생각할 수 있습니다. 사실이며 간단한 경우에는 효과가 있습니다. 그러나 이 기사에 제시된 사용 사례에서는 모든 필수 필드가 채워질 때까지 제출 버튼을 완전히 비활성화 / 숨기기를 원합니다. 이 기능은 더 확장 될 수 있으며, 내 지식으로는 자체적으로 속성이 필요한 것은 아닙니다. 필수 속성은 시맨틱 HTML의 좋은 출발점이지만 풍부한 사용자 경험을 위해서는 JavaScript가 필요합니다.
언급 할 가치가 있는 또 다른 사항은 이 기사에서 논의 된 구현은 입력 필드에 값이 있는지 여부 만 확인한다는 것입니다. 무언가를 놓친 경우 사용자에게 정규식 / 패턴 일치 또는 유용한 메시지를 제공하기 위해 후크를 함께 구성하면 더 나은 환경을 제공 할 수 있습니다. 그러나 이는 디자인 트레이드 오프로 간주되며 Formik와 같은 "본격적인"솔루션에 도달하기에 적절한 시점 일 수 있습니다.
다시 한 번, 데모뿐만 아니라 모든 코드를 보려면 여기에 CodeSandbox가 있습니다.
- 이전글React Hooks가 Redux를 대체합니까? (1) 19.08.13
- 다음글자신 만의 React 커스텀 훅 작성 (3) 19.08.09