I have a very simple app that lets you log in and then displays a dashboard. The design process with React and Redux is very simple :
- I have two React components : Login and Dashboard
- I store a boolean isAuthenticated in my state tree
Now some remarks :
- The Login component can only be seen if isAuthenticated is false
- The Dashboard component can only be seen if isAuthenticated is true
- A button in the Login component sets isAuthentication to true
- A button in the Dashboard component sets isAuthentication to false
How should I implement this in React ? There is at least two possibilities :
- using routing : / redirects to /login if authenticated or /dashboard if not. Also /login redirects to /dashboard if authenticated and /dashboard redirects to /login if not authenticated
- introduce an App component that renders either Login or Dashboard depending on isAuthenticated
Here is the implementation of the second proposal :
const Login = (props) => (
<div className="login">
<p>Login page</p>
<input type="button" value="Log in" onClick={props.toggleAuthentication}/>
</div>
)
const Dashboard = (props) => (
<div className="dashboard">
<p>Dashboard page</p>
<input type="button" value="Log out" onClick={props.toggleAuthentication}/>
</div>
)
class App extends React.Component {
constructor(props){
super(props)
this.state = {isAuthenticated: false}
}
toggleAuthentication(){
this.setState({isAuthenticated: !this.state.isAuthenticated})
}
render() {
if(!this.state.isAuthenticated){
return <Login toggleAuthentication={()=>this.toggleAuthentication()}/>
} else {
return <Dashboard toggleAuthentication={()=>this.toggleAuthentication()}/>
}
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);