elderjs icon indicating copy to clipboard operation
elderjs copied to clipboard

on:click on Component

Open rjsandman opened this issue 5 years ago • 4 comments

Is there anything special you need to do to get an on:click function to work on a Component?

rjsandman avatar Oct 09 '20 21:10 rjsandman

@sandman18 if you’re hydrating it. Wrap it in another component. hydrate-client only mounts a new component and on:click is not supported in mount code.

nickreese avatar Oct 09 '20 23:10 nickreese

Okay, can you help me reason for a second. You only need to hydrate components that have some sort of function correct? So, let's say I have two components, a section component and a button component. The button component is being used in the section component. Right now my function is in the section component and I am calling it when clicking the button component. In order to make this work I will need to hydrate the section component. This seems counter intuitive though because we don't want to hydrate everything in the section..right? So rather, should I move the functionality inside the button component and just hydrate the button?

rjsandman avatar Oct 10 '20 17:10 rjsandman

Yep. Only hydrate components that need client interactivity. In general this means hydrating the lowest level possible component in a tree. So unless you need to change something in your “section” component you probably don't need to hydrate it.

nickreese avatar Oct 10 '20 17:10 nickreese

Hello, I'm trying to follow this thread and also get on:click to work for a component. I'm not quite getting the hydration. With stock template, I have a "Button" component with the following example:

<script>
	function handleClick() {
		alert('clicked')
	}
</script>

<button on:click={handleClick}>
	Click me
</button>

Then within Layout.svelte, I did the following:

<script>
	import Button from '../components/Button.svelte'
</script>


<main>
	<h1>Hello World</h1>
  <br/>
  <Button hydrate-client={{}}/>
</main>

But no alerts. Am I missing something?

EDIT: I just reread it and saw you wrote on:click is not supported in mount code. What then would you suggest is used if the user needs to click? (ie, in the case of a carousel, the prev/next button)

TotalLag avatar Nov 27 '21 06:11 TotalLag