Home > Software engineering >  (svelte) how can I access previus component props from component
(svelte) how can I access previus component props from component

Time:09-19

how can I access a prop from a same-named component in the same container?

<Container>
 <Line x={10} y={12}>
 <Line x={14} y={8}>
 <Line x={50} y={30}>
</Container>

so the second <Line> get these props (x, y)
but also the previous Line props (without that user need to specify it)

so in the second Line Case, it get the 14 and 8, but needs to get also 10, and 12

in the line.svelte:

<script>
  export let x;
  export let y;
</script>

<div style="top: {x}px; left: {y}px;" />

I need to get the previous x, y because I need to do some calculation and find the angle and connect the 2 lines (and I know the formula).

My idea is something like document.querySelector("Line")[thisComponetIndex - 1].x; but isn't possible in Svelte since is compiled.

CodePudding user response:

If the lines are related, I would recommend processing them in a single component, rather than individually. Inter-component communication in Svelte is a bit cumbersome.

So instead of the current markup you do something like:

<Lines items={[
    { x: 10, y: 12 },
    { x: 14, y: 8 },
    { x: 50, y: 30 },
]}/>

Then, inside the component you can process the items with {#each} and use its index to also access the previous item.

{#each items as item, index}
  {@const previousItem = items[index - 1]}
  ...
{/each}

You can still use the Line component here, if that is useful to you.

  • Related