Skip to content

Instantly share code, notes, and snippets.

@nateinaction
Last active November 21, 2022 14:44
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save nateinaction/fb6b6a11fcf385c82a6a9f2da7aeb4bf to your computer and use it in GitHub Desktop.
Save nateinaction/fb6b6a11fcf385c82a6a9f2da7aeb4bf to your computer and use it in GitHub Desktop.
This is a version of Facebook's React Conditional Rendering example modified to support firebase authentication.
/*
* This is a version of Facebook's React Conditional Rendering
* example modified to support firebase authentication.
* https://facebook.github.io/react/docs/conditional-rendering.html
*/
import React, { Component, PropTypes } from 'react';
import * as firebase from 'firebase';
function UserAvatar(props) {
return (
<img
className='avatar'
alt={props.name + "'s profile picture"}
src={props.photoUrl} />
);
}
UserAvatar.propTypes = {
name: PropTypes.string,
src: PropTypes.string
}
function UserGreeting(props) {
return (
<span>Hi {props.name}!</span>
);
}
UserGreeting.propTypes = {
name: PropTypes.string
}
function GuestGreeting(props) {
return <span>You are not signed in.</span>;
}
function Greeting(props) {
if (props.auth) {
return (
<div className='user-meta'>
<UserAvatar
name={props.auth.displayName}
photoUrl={props.auth.photoURL} />
<UserGreeting
name={props.auth.displayName} />
</div>
)
}
return <GuestGreeting />;
}
function SignInButton(props) {
return (
<button onClick={props.onClick}>
Sign in
</button>
);
}
function SignOutButton(props) {
return (
<button onClick={props.onClick}>
Sign out
</button>
);
}
class AuthControl extends Component {
constructor(props) {
super(props);
this.handleSignInClick = this.handleSignInClick.bind(this);
this.handleSignOutClick = this.handleSignOutClick.bind(this);
this.state = {auth: false};
}
handleSignInClick() {
const provider = new firebase.auth.GoogleAuthProvider();
const auth = firebase.auth();
auth.signInWithPopup(provider);
}
handleSignOutClick() {
const auth = firebase.auth();
auth.signOut();
}
componentDidMount() { // check to see if already signed in.
const auth = firebase.auth();
auth.onAuthStateChanged((user) => {
if (user) {
this.setState({auth: user});
this.registerUser(user);
} else {
this.setState({auth: false});
}
});
}
registerUser(user) {
const userRef = firebase.database().ref('users/' + user.uid);
userRef.update({
name: user.displayName,
email: user.email,
photoUrl: user.photoURL,
lastConnectTime: new Date()
});
}
render() {
const auth = this.state.auth;
let button = null;
if (auth) {
button = <SignOutButton onClick={this.handleSignOutClick} />;
} else {
button = <SignInButton onClick={this.handleSignInClick} />;
}
return (
<div className='auth'>
<Greeting auth={auth} />
{button}
</div>
);
}
}
export default AuthControl;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment