React-Typescript-useState issue

import Button from "./assets/components/Button";
import Alert from "./assets/components/Alert";
import UserInput from "./assets/components/ToDo";
import React from "react";
import { useState } from "react";

function App() {
  let myToDos: Array<string> = [];
  const [alertVisible, setAlertVisibility] = useState(false);
  const [toDos, setToDos] = useState(myToDos);
  const [inputValue, setInputValue] = useState("");

  const onChange: React.ComponentProps<"input">["onChange"] = (e) => {
  const onClick: React.ComponentProps<"button">["onClick"] = (e) => {
    setToDos([...myToDos, inputValue]);

  return (
      {alertVisible && (
        <Alert onClose={() => setAlertVisibility(false)}>My Message</Alert>
      <Button onClick={() => setAlertVisibility(true)}>Click Me!</Button>
      <UserInput />
      <div id="to-do">
          <h1>To-do Tasks: </h1>
          <input id="inputTasks" value={inputValue} onChange={onChange}></input>
          <button type="submit" onClick={onClick}>
            Add Todo

          {, index) => (
            <li key={index}>

export default App;

When I click Add Todo , the

  • element got rendered for a second and disappeared. I don’t know what’s wrong with my code.

  • 1 Like

    Hello, firstly you don’t need the myToDos variable; you can manage it with an empty array in useState.

    const [toDos, setToDos] = useState<string[]>([]);

    Also you don’t need to button type="submit" you already using state to manage inputValue with onChange function, you can use button type="button" and related with this preventDefault doesn’t seem right.

    It should be like this;


    Because of this your page has been reload after toDos rendering inside to <ul> element correctly and they get dissapear.

    Also you can create and use a different component to show the <ul> element in the DOM using Additionally, you can add another condition to render it only if toDos has any elements.

    I hope this will help this situation, happy coding :slightly_smiling_face:.

    1 Like

    Thanks. Problem solved. It works when i change the type of the button to “button” while everything else remains the same. I started out with the array typescript you suggested but i changed because i thought it was an issue.

    Great :+1:. You’re welcome :slightly_smiling_face: