Home  >  Q&A  >  body text

Dynamically creating new components does not work in svelte

So I'm trying to create a new component when a button is pressed.

This is where the button is:

<input type="color" id="todo-color" bind:value={todoColor} />
  <input
    type="text"
    id="todo-content"
    placeholder="Todo"
    bind:value={todoContent}
  />
  <input
    type="checkbox"
    name="isImportant"
    id="is-important"
    bind:checked={todoImportance}
  />
  <button on:click={createTodo}>Create todo</button>

The function called is this:

let todoContent: string;
  let todoColor: string = "#ff0000";
  let todoImportance: any = "default";
  const createTodo = () => {
    todoImportance
      ? (todoImportance = "important")
      : (todoImportance = "default");

    console.log(todoColor, todoContent, todoImportance);

    new Task({
      target: document.querySelector('#basic-todos'),
      todoContent,
      todoColor,
      todoImportance,
    });
  };

These three props must be strings, that's what they are. But I always have no definition of these three props.

I have no idea what's wrong with this code at all, if you have a solution or another way to do this I'll take it all :)

P粉133321839P粉133321839202 days ago439

reply all(1)I'll reply

  • P粉763748806

    P粉7637488062024-04-01 11:32:33

    Props as properties props Passed:

    new Task({
      target: document.querySelector('#basic-todos'),
      props: {
        todoContent,
        todoColor,
        todoImportance,
      },
    });
    

    document

    (Assuming these are the correct property names.)

    But as mentioned above, this is not how to create a to-do list in Svelte. Data should be added to the list and items should be created declaratively using {#each}.

    Approximately as follows:

    let items = [];
    // ...
    const createTodo = () => {
      // [collect/prepare data]
    
      items = [...items, item];
    };
    
    {#each items as { content, color, importance }}
      
    {/each}
    

    If items are added/removed in the middle, {#each} requires a key, see documentation.

    reply
    0
  • Cancelreply