0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

useRefで連想配列を使う(Typescript)

Posted at

タイトル通りですが、意外に連想配列を渡す例がネットで見つからなくて困ったので、メモ程度に書いています。

App.tsx
type TodoType = {
  id: number;
  todo: string;
  isDone: boolean;
};

const App: React.FC = () => {
  const [inputText, setInputText] = useState<string>("");
  const text = useRef<TodoType[]>([]);

  const changeText = () => {
    text.current.push({
      id: text.current.length++,
      todo: inputText,
      isDone: false
    });
  };

  const onChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
    setInputText(e.target.value);
  };

  return (
    <>
      <input type="text" onChange={onChange} value={inputText} />
      <button onClick={changeText}>Change</button>
      <p>
        {text.current.map((i) => (
          <li key={i.id}>{i.todo}</li>
        ))}
      </p>
    </>
  );
};
export default App;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?