How can I read an attribute value of a svelte component

Viewed 1977

Component.svelte

<script>
  export let hiddenStatus;
</script>

<div class:hidden={hiddenStatus}></div>

App.svelte

<script>
  import Component from "./Component.svelte";
</script>

<Component hiddenStatus={true}/>
{Component.hiddenStatus}

When I try to get that attribute value of hiddenStatus it displays as undefined. How can I solve this?

1 Answers

You can use the bind:this component directive to interact with the component instance programmatically.

Note that props cannot be read directly from the component instance unless you are compiling with accessors set to true or <svelte:options accessors/>.

Example

<!-- Component.svelte -->
<script>
  export let hiddenStatus;
</script>

<div class:hidden={hiddenStatus}></div>

<!-- App.svelte -->
<script>
  import { onMount } from "svelte";
  import Component from "./Component.svelte";

  let component;
    
  onMount(() => {
    console.log(component.hiddenStatus);
  });
</script>

<Component hiddenStatus={true} bind:this={component}/>
Related