Sveltekit: Tell me how to change the hidden value from "./Cart" to "./Navbar"

Viewed 40

I want to change the value of true to false from the Navbar.svelte component

index.svelte

<script>
    import Cart from "../lib/Cart.svelte";
    import Navbar from "../lib/Navbar.svelte";
</script>

<div>
    <Cart />
    <Navbar/>
</div>

In this file, the initial value is true

Cart.svelte

<script>
    let hidden = true
</script>

{#if hidden}
<div class="box">
<button on:click={() => hidden = false}>x</button>
</div>
{/if}

<style>
    .box {
        width: 64px;
        height: 64px;
        background-color: black;
    }
</style>

It is necessary to change the value in cart.svelte from true to false from this component when clicking on the button

Navbar.svelte

<script>
    
</script>

<div>
    <button>HIDDEN</button>
</div>
1 Answers

One way to modify the value in the other component would be via the parent and using bind: REPL

App.svelte
<script>
    import Cart from "./Cart.svelte";
    import Navbar from "./Navbar.svelte";

    let cartHidden
</script>

<div>
    <Cart {cartHidden}/>
    <Navbar bind:cartHidden/>
</div>
Cart.svelte
<script>
    export let cartHidden = true
</script>

{#if cartHidden}
<button on:click={() => cartHidden = false}>x</button>
{/if}
Navbar.svelte
<script>
    export let cartHidden
</script>

<div>
    <button on:click={() => cartHidden = false}>XXX</button>
</div>

Or alternatively and I'd say better make the variable a store REPL

App.svelte
<script>
    import Cart from "./Cart.svelte";
    import Navbar from "./Navbar.svelte";
</script>

<div>
    <Cart />
    <Navbar />
</div>
Cart.svelte
<script>
    import {cartHidden} from './cartHidden'
</script>

{#if $cartHidden}
<button on:click={() => $cartHidden = false}>x</button>
{/if}
Navbar.svelte
<script>
    import {cartHidden} from './cartHidden'
</script>

<div>
    <button on:click={() => $cartHidden = false}>XXX</button>
</div>
cartHidden.js
import {writable} from 'svelte/store'

export const cartHidden = writable(true)

I would probably revert the hidden to visible since I find
visible - !visible
better to read than
!hidden - hidden

Related