rishavs / vanillajs-spa

a simple SPA in vanilla js
343 stars 107 forks source link

Rerendering a component #3

Closed abitofBaileys closed 5 years ago

abitofBaileys commented 5 years ago

Hello!

Great SPA and project to learn from!

I have a question regarding the reloading of components without reloading the entire page. Is there a way you recommend e.g. reloading the Navbar component programmatically?

Thanks! 👍

rishavs commented 5 years ago

thats how the navbar is actually set up. see the code at; https://github.com/rishavs/vanillajs-spa/blob/master/src/views/components/Navbar.js

The render function is not accepting any params right now. But you can easily add a param (say "isLoggedIn" ) everytime you call the navbar for page render.

in the actual HTML code for the navbar component, you can say that if isLoggedIn is true then render a button for logout. else show button for login.

                            <div class="navbar-item">
                                <div class="buttons">
                                    <a class="button is-primary" href="/#/register">
                                        <strong>Sign up</strong>
                                    </a>
                                    <a class="button is-light">
                                        Log in
                                    </a>
                                </div>
                            </div>
                        </div>

A slightly different execution of the same idea is in a different repo of mine; https://github.com/rishavs/Verdin/blob/master/src/views/components/Navbar.js

Here instead of actually calling the render function with specific params, i am simply just checking if i have saved the login state in my localStorage.

                           ${ window.localStorage['_user_email']
                            ?
                            /*html*/`
                            <div class="navbar-item">
                                // button for signin
                            </div>
                            `
                            :
                            /*html*/`
                            <div class="navbar-item">
                                // button for signout
                            </div>`

Let me know if that helped.

abitofBaileys commented 5 years ago

Thanks for the quick reply!

I figured pretty much the same, just wanted to confirm whether that was the intended an correct approach in this case, but your alternative implementation is also interesting to see.

Have a nice day!