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:
- Create a new folder: src/pages/.
- 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>
)
}
- 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 />}
- 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'
- Additionally, import the ThemeContext and the StateContext:
import { ThemeContext, StateContext } from '../contexts'
- 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 (
- Now, we import the HeaderBar component in src/App.js:
import HeaderBar from './pages/HeaderBar'
- 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.