Back

Technologies:

javascriptjavascript
avatar
Tolerim
a day ago

Svelte does not allow for dynamic creation of new components.

My goal is to create a new component when a button is pressed, and I'm looking for help with my code.

The button, along with relevant inputs, are shown below:

<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>
This is the function that is called when the button is pressed:

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,
    });
  };
I've ensured that all three props are strings, but they continue to return as undefined. I'm not sure what's causing this issue, so any assistance or alternative approaches would be greatly appreciated!

Answers(1)
avatar
Tolerim
a day ago
Verified Answer
It seems like the variables for todoContent, todoColor, and todoImportance are defined outside the createTodo function but are being set inside the function. This could be causing issues with scoping and the values not being passed correctly to the Task constructor. One solution could be to define the variables inside the createTodo function and pass them directly as arguments to the Task constructor. Here's an example:
const createTodo = () => {
  const todoContent = document.querySelector("#todo-content").value;
  const todoColor = document.querySelector("#todo-color").value;
  const todoImportance = document.querySelector("#is-important").checked
    ? "important"
    : "default";

  console.log(todoColor, todoContent, todoImportance);

  new Task({
    target: document.querySelector("#basic-todos"),
    todoContent,
    todoColor,
    todoImportance,
  });
};
In this example, we are using document.querySelector to get the values of the input fields directly inside the createTodo function and then passing them as arguments to the Task constructor. Another solution could be to use a state management library like Redux or React's useState hook to manage the state of the input values and pass them down as props to the Task component. This would require more setup and configuration but can be useful for larger applications with more complex state management needs.
;