Skip to content

Instantly share code, notes, and snippets.

@camjackson
Last active November 17, 2019 09:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save camjackson/c0b60e8039946df0add8 to your computer and use it in GitHub Desktop.
Save camjackson/c0b60e8039946df0add8 to your computer and use it in GitHub Desktop.
Basic stateless React.js form
/*
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