I'm new to web development and started learning ReactJS.
Till now there is no problem with building simple web apps.
Now I wanted to use authentication using Firebase.
I know how to authenticate a user using Firebase but I'm not able to get how to design frontend to restrict access to certain pages.
Previously, I used PHP and in that I used session
variable and include
to include the parts of HTML to show to the user.
But I don't know how to do it in ReactJS using Firebase.
Initial and failed approach:
I thought of updating this.state.loggedIn
and using that to show the component. But this is not a correct way because I'm sending both the components to display and easily we can change the state of a component using React developer extension in Chrome.
This is my main index.js code:
import React from 'react';
import ReactDOM from 'react-dom';
import Login from './components/Login/Login';
import Home from './components/Home/Home';
import fire from './components/Fire';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
loggedIn: false,
};
this.authListener = this.authListener.bind(this);
}
componentDidMount() {
this.authListener();
}
authListener() {
fire.auth().onAuthStateChanged(user => {
if (user) {
// User is signed in.
console.log(user);
this.setState({
loggedIn: true
})
} else {
// No user is signed in.
this.setState({
loggedIn: false
});
}
});
}
render() {
return (
<div>
{this.state.loggedIn ? <Home/> : <Login/>}
</div>
);
}
}
ReactDOM.render(
<App/>, document.getElementById('app'));
And In Login.js, I'm calling the Firebase authentication function.
Just the snippet:
fire
.auth()
.signInWithEmailAndPassword(this.state.email, this.state.password)
.catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(error);
// ...
});
The authentication is working fine and I can see it in the console log.
So, how should I do it in ReactJS + Firebase to authenticate?(Is it posible without using any other packages like react-routes etc?)
Or should I be using Cloud functions for this?