How do I reference a Svelte component's parent component?

5.4k views Asked by At

Per the Svelte documentation on Props I am using props to pass a reference to the parent component to a child.

Props, short for 'properties', are the means by which you pass data down from a parent to a child component

That's exactly what I want to do. Here is a Svelte REPL with my code, that is also copied below:

My parent is App.html:

<div class='widget-container'>
    <Widget foo bar="static" {baz}/>
</div>

<script>
    import Widget from './Widget.html';

    export default {
        data: function(){ 
            return {
                baz: 'click me and check the console'
            }
        },
        components: {
            Widget
        }
    };
</script>

The child component is Widget.html:

<p>foo: {foo}</p>
<p>bar: {bar}</p>
<p>baz: {baz}</p>

<script>
    export default {
        oncreate: function(){
            window.document.body.addEventListener('click', function(event){
                console.log(`Clicked!, ${baz}`)
            });
        }
    }

</script>   

Thanks to the props, the HTML <p> elements can clearly reference the parent. However how can I reference the values in the parent component in the child component's JavaScript?

1

There are 1 answers

4
Rich Harris On BEST ANSWER

Inside lifecycle hooks and methods, access state with this.get():

<p>foo: {foo}</p>
<p>bar: {bar}</p>
<p>baz: {baz}</p>

<script>
    export default {
        oncreate: function(){
            window.document.body.addEventListener('click', () => {
                const { baz } = this.get();
                console.log(`Clicked!, ${baz}`)
            });
        }
    }l
</script>