Skip to content

Instantly share code, notes, and snippets.

@JacobKnaack
Last active June 20, 2019 05:40
Show Gist options
  • Save JacobKnaack/5ebe3e02f74525283e84ef939829ce4b to your computer and use it in GitHub Desktop.
Save JacobKnaack/5ebe3e02f74525283e84ef939829ce4b to your computer and use it in GitHub Desktop.
Cosmic Messenger login form component.
import React from 'react';
import { Redirect } from 'react-router-dom';
import { socket } from '../../lib/socket.js';
import axios from 'axios';
import Logo from '../../../public/logo.svg';
class LoginForm extends React.Component {
constructor() {
super()
this.state = {
username: '',
requestError: {},
}
this.handleInput = this.handleInput.bind(this)
this.handleRegister = this.handleRegister.bind(this)
}
render() {
if (!Object.keys(this.props.user).length) {
return (
<div className="loginForm-container">
<img src={Logo}/>
<form id="loginForm">
<h5><strong>Hi!</strong> Welcome to Cosmic Messenger</h5>
<p>Please give us a little bit of info.</p>
<div>
{this.state.requestError.message
? <label>That Username is already in use</label>
: <label>Enter a Username</label>
}
<input
name="username"
placeholder="Some name you like..."
style={styles.userInput}
value={this.state.username}
onChange={this.handleInput}
autoFocus
/>
</div>
<button onClick={this.handleRegister}>
Start Chatting
</button>
</form>
<footer>
<a href="https://cosmicjs.com/add-bucket?import_bucket=5cf1605916e7ec14adabbb89"><img src="https://cdn.cosmicjs.com/51fe54d0-4f6e-11e9-9f32-8d001da69630-powered-by-cosmicjs.svg" /></a>
</footer>
</div>
)
}
return <Redirect to={`/${this.props.user.name.replace(/\s+/g, '-').toLowerCase()}`} />
}
handleInput(e) {
if (this.state.requestError.message) {
this.setState({ requestError: {} })
}
const { name, value } = e.target
this.setState({ [name]: value })
}
handleRegister(e) {
e.preventDefault()
axios.post(`${__API_URL__}/register`, {
username: this.state.username,
})
.then(res => {
this.props.handleUser(res.data);
socket.emit('register', res.data);
})
.catch(err => this.setState({ requestError: err }));
}
}
export default LoginForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment