Passing the user to CreatePost

As you might have noticed, the CreatePost component still uses the hardcoded username. To be able to access the user value there, we need to move the Hook from the UserBar component, to the App component.

Let's refactor the definition of the user State Hook now:

  1. Edit src/user/UserBar.js, and cut/remove the Hook definition that is there:
    const [ user, setUser ] = useState('')
  1. Then, we edit the function definition, and accept these two values as props:
export default function UserBar ({ user, setUser }) {
  1. Now, we edit src/App.js, and import the useState Hook there:
import React, { useState } from 'react'
  1. Next, we remove the static user value definition:
    const user = 'Daniel Bugl'
  1. Then, we insert the user State Hook that we cut earlier into the App component function:
    const [ user, setUser ] = useState('')
  1. Now, we can pass user and setUser as props to the UserBar component:
            <UserBar user={user} setUser={setUser} />
The user state is a global state, so we are going to need it in many components across the app. At the moment, this means that we need to pass down the user value and the setUser function to each component that needs it. In a future chapter, we are going to learn about React Context Hooks, which solve the problem of having to pass down props in such a way.
  1. Finally, we only show the CreatePost component when the user is logged in. To do this, we use a pattern, which allows us to show a component based on a condition:
            {user && <CreatePost user={user} />}

Now, the users feature is fully implemented—we can use the Login and Register components, and the user value also gets passed to the CreatePost component!

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

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