Creating the HeaderBar component

First of all, we are going to refactor some contents of our App component into a HeaderBar component. The HeaderBar component will contain everything that we want to display on every page: the Header, UserBar, ChangeTheme, and CreatePost components.

Let's start creating the HeaderBar component:

  1. Create a new folder: src/pages/.
  2. Create a new file, src/pages/HeaderBar.js, import React (with the useContext Hook), and define the component there. It will accept the setTheme function as prop:
import React, { useContext } from 'react'

export default function HeaderBar ({ setTheme }) {
return (
<div>
</div>
)
}
  1. Now, cut the following code from the src/App.js component, and insert it between the <div> tags of the HeaderBar component:
            <Header text="React Hooks Blog" />
<ChangeTheme theme={theme} setTheme={setTheme} />
<br />
<React.Suspense fallback={"Loading..."}>
<UserBar />
</React.Suspense>
<br />
{user && <CreatePost />}
  1. Also, cut the following import statements (and adjust the paths) from src/App.js and insert them at the beginning of the src/pages/HeaderBar.js file, after the import React from 'react' statement:
import CreatePost from '../post/CreatePost'
import UserBar from '../user/UserBar'
import Header from '../Header'
import ChangeTheme from '../ChangeTheme'
  1. Additionally, import the ThemeContext and the StateContext:
import { ThemeContext, StateContext } from '../contexts'
  1. Then, define two Context Hooks for the theme and state, and pull the user variable out of the state object in src/pages/HeaderBar.js, as we need it for a conditional check to determine whether we should render the CreatePost component:
export default function HeaderBar ({ setTheme }) {
const theme = useContext(ThemeContext)

const { state } = useContext(StateContext)
const { user } = state

return (
  1. Now, we import the HeaderBar component in src/App.js:
import HeaderBar from './pages/HeaderBar'
  1. Finally, we render the HeaderBar component in src/App.js:
        <div style={{ padding: 8 }}>
<HeaderBar setTheme={setTheme} />
<hr />

Now, we have a separate component for the HeaderBar, which will be shown on all pages. Next, we move on to creating the HomePage component.

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

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