Skip to content
This repository was archived by the owner on Jan 11, 2023. It is now read-only.
This repository was archived by the owner on Jan 11, 2023. It is now read-only.

Is it possible to pass an event handler to slot? #731

@bausk

Description

@bausk

Environment

Node Version: v8.16.0 , OS: Windows 10, npm version : 6.1.0 .

Setting up

I'm using the default Sapper template without any additional dependencies, with a child component added to Nav.svelte:

// Nav.svelte
<script>
	import Login from './Login.svelte';
	...
</script>
...
		<li>
			<Login let:onclick={onclick}>
				<button onClick={onclick}>
					Click me!
				</button>
			</Login>
		</li>

The Problem

I'm exploring the standard svelte-sapper template and I want to add a button in the Nav component that will excute some login logic. I also want to separate the button's presentation and logic so I try to use slots for this. In the added component, Login.svelte:

<script>
	let onclick;
	onclick = function() {
		window.alert('ALERT');
        // Browser-specific Auth0 logic should go here
	};
</script>

<div>
	<slot onclick={onclick}></slot>
</div>

There are two issues here:

  1. The code gets executed on server side before hydration (evidenced by a 500 error briefly shown on server route execution). After some research I see that this should be solved by simply checking for typeof window?

  2. When I click the button I get (in the browser console):

function() {
--------^ Uncaught SyntaxError: Unexpected token (
		window.alert('ALERT');
	}

What I'm trying to achieve is basically passing the event handler to a slot. Using recommendations in the docs for making a client-only component doesn't seem to work with slots (see below).

Attempts at solving

I read about making code execute on client only and as much as I dislike all the boilerplate, I tried to do that and apparently slots are not passed on to child components so that to my understanding doesn't work.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions