1

I need to handle 2 different header in my application:

  • Menu
  • A simple Bar with title

Firstly I’m thinking by using the local storage to save the menu I want to showUp (localStorage.setItem('menu', 'default’);)
So when I’m in a component who don’t need the menu but just the simple bar I just resetting the localStorage like this : localStorage.setItem('menu', ‘bar’);

But this idea (I know it's not the best) didn’t re-render my header.

 What should I do to handle this case ?

In my render I have something like this :

render() {
        let menu = localStorage.getItem('menu');
        return (
            <header>
                {menu === 'bar' ? <TopBar/> : <MenuBar/>}
            </header>
        )
    }
3
  • why don`t using your header where your routes are locating? Commented Jun 13, 2019 at 13:55
  • @Samamone can you please check my answer? If you have any questions or feedback, please feel to write. Commented Jun 20, 2019 at 17:12
  • @JordanEnev Hey, sorry I moved on to something else this week, I'll be back to you next week. I think I'll try second suggestion, which I think is the most appropriate for my case. I will share my code when it works, otherwise I'll tell you.. But I think you put me on the right track :) Commented Jun 21, 2019 at 15:35

1 Answer 1

2

Your Header isn't rerendered, because its props / state aren't changed. You're changing only the localStorage and this won't rerender your component.

I can suggest to you two approaches:

1. Depending on which route you are, just use the proper Header:

// Home.js
const Home = props => <>
  <MenuBar />
  // The rest components of your page
</>


// Inside.js
const Inside = props => <>
  <TopBar />
  // The rest components of your page
</>

2. If you have a <PageLayout /> component, you can use a prop for conditionally render the Header:

<PageLayout /> is such a component, where we can reuse the page layout components composition. Every page has a header, body, footer. Instead of duplicating the same components structure in all the pages, it will be better to abstract the layout structure in <PageLayout />.

const PageLayout = ({ header === 'default', children }) => <>
 <header>
   { header === 'bar' ? <TopBar /> : <MenuBar /> }
 </header>
 <body>
   {children}
 </body>
 <Footer />
</>

// Home.js - Here will use the `default` Header
const Home = props => <PageLayout>
  // The rest components of your page
</PageLayout

// Inside.js - Here we will use <TopBar /> 
const Inside = props => <PageLayout header='bar'>
  // The rest components of your page
</PageLayout

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.