SystemParadox
SystemParadox

Reputation: 8647

Svelte alias/rename props

Is there any way to rename/alias props in svelte?

For example, if I have a component which takes a foo prop but I also want a foo local variable for the current state, is there any way to rename the incoming prop a bit like this:

export let foo as forceFoo;
let foo = forceFoo | null;

Normally the correct answer is one of these two:

  1. Rename the prop to something like initialFoo
  2. Rename the state

Renaming the prop is not appropriate in this case - it's the public API of the component and it's not an initial state, it's an optional override that forces the value of that field.

Renaming the state is ok for a single field and usually works well for generic components, but becomes horrible and unwieldy when the component is a form with many fields and has to pass those fields on to a save function that expects them to have the right names.

Upvotes: 5

Views: 1688

Answers (1)

rixo
rixo

Reputation: 25001

The proper syntax is the following:

<script>
  // aliased prop
  let forceFoo
  export { forceFoo as foo }

  // local state
  let foo = forceFoo
</script>

Upvotes: 10

Related Questions