Last active
November 17, 2019 09:18
-
-
Save camjackson/c0b60e8039946df0add8 to your computer and use it in GitHub Desktop.
Basic stateless React.js form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This is obviously a very basic example. It takes props to render the inputs with their values, and | |
to render any error state. It also takes props to update the state, or submit the form. | |
*/ | |
const LoginForm = props => ( | |
<form onSubmit={props.onSubmit}> | |
<input type="text" name="username" onChange={props.onChangeUsername} value={props.username}/> | |
{ props.userNameError && <span class="error">{ props.usernameError }</span> } | |
<input type="password" name="password" onChange={props.onChangePassword} value={props.password}/> | |
{ props.passwordError && <span class="error">{ props.passwordError }</span> } | |
<input type="submit" value="Log in"/> | |
</form> | |
); | |
LoginForm.propTypes = { | |
username: React.PropTypes.string.isRequired, | |
usernameError: React.PropTypes.string.isRequired, | |
password: React.PropTypes.string.isRequired, | |
passwordError: React.PropTypes.string.isRequired, | |
onChangeUsername: React.PropTypes.func.isRequired, | |
onChangePassword: React.PropTypes.func.isRequired, | |
onSubmit: React.PropTypes.func.isRequired | |
}; | |
export default LoginForm; | |
/* | |
This is just one approach - it may very well be overkill to notify a parent / dispatch an action | |
on every keypress. Instead, you could write a stateful component where the inputs' onChange events | |
change the local, intermediate state, and then onBlur (and probably also onSubmit) is what causes | |
that state to leave the component and be persisted somewhere else. | |
Both of those approaches are assuming that the state is ultimately stored outside the form component. | |
I like to put it in a redux store, because a) you can put business logic like validation either in | |
a reducer, or a reselect selector, and b) when submitting the form you can dispatch a thunk action | |
which reads the store using getState, and then submits it. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment