The UserBar component

Now it is time to put our user-related components together into a UserBar component. Here we are going to conditionally show either the Login and Register components, or the Logout component, depending on whether the user is already logged in or not.

Let's start implementing the UserBar component:

  1. First, we create a new src/user/UserBar.js file, and import React as well as the three components that we defined:
import React from 'react'

import Login from './Login'
import Logout from './Logout'
import Register from './Register'
  1. Next, we define our function component, and a value for the user. For now, we just save it in a static variable:
export default function UserBar () {
const user = ''
  1. Then, we check whether the user is logged in or not. If the user is logged in, we display the Logout component, and pass the user value to it:
    if (user) {
return <Logout user={user} />
  1. Otherwise, we show the Login and Register components. Here, we can use React.Fragment instead of a <div> container element. This keeps our UI tree clean, as the components will simply be rendered side by side, instead of being wrapped in another element:
    } else {
return (
<React.Fragment>
<Login />
<Register />
</React.Fragment>
)
}
}
  1. Again, we edit src/App.js, and now we show our UserBar component:
import React from 'react'

import UserBar from './user/UserBar'

export default function App () {
return <UserBar />
}
  1. As we can see, it works! We now show both the Login and Register components:

Our UserBar component, showing both the Login and Register components
  1. Next, we can edit the src/user/UserBar.js file, and set the user value to a string:
        const user = 'Daniel Bugl'
  1. After doing so, our app now shows the Logout component:

Our app showing the Logout component after defining the user value

Later on in this chapter, we are going to add Hooks to our application, so that we can log in and have the state change dynamically without having to edit the code!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.100.180