⚛️ Introduction
Managing dynamic arrays in React is a common task — whether you're working with forms, lists, or user selections. In this post, we'll build a TypeScript React component that:
- Adds a new item to an array on input and button click
- Renders checkboxes to control which items are selected
- Removes unchecked items from the array
Let’s dive into how to make your array state fully interactive!
📌 Use Case
You want a list where:
- Users can type a value into an input and click Add
- Each item appears in a list with a checkbox
- Unchecking a checkbox removes that value from the array
- Rechecking it adds it back
✅ Full Example
Here’s how to make that happen with useState
and TypeScript:
tsx
import React, { useState } from 'react';
const MyComponent: React.FC = () => {
const [values, setValues] = useState<string[]>([]);
const [inputValue, setInputValue] = useState<string>("");
const [checkedItems, setCheckedItems] = useState<{ [key: string]: boolean }>({});
// Track input field
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
};
// Add value to list and mark it as checked
const handleAddValue = () => {
if (inputValue.trim() !== "" && !checkedItems[inputValue]) {
setCheckedItems(prev => ({ ...prev, [inputValue]: true }));
setValues(prev => [...prev, inputValue]);
setInputValue("");
}
};
// Toggle checkbox and update values
const handleToggleCheck = (value: string) => {
const isChecked = !checkedItems[value];
setCheckedItems(prev => ({ ...prev, [value]: isChecked }));
if (isChecked) {
setValues(prev => [...prev, value]);
} else {
setValues(prev => prev.filter(item => item !== value));
}
};
return (
<div>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
placeholder="Add new item"
/>
<button onClick={handleAddValue}>Add</button>
<ul>
{Object.keys(checkedItems).map((value, index) => (
<li key={index}>
<label>
<input
type="checkbox"
checked={checkedItems[value]}
onChange={() => handleToggleCheck(value)}
/>
{value}
</label>
</li>
))}
</ul>
<div>
<h4>Selected values:</h4>
<pre>{JSON.stringify(values, null, 2)}</pre>
</div>
</div>
);
};
export default MyComponent;
🔍 How It Works
values
holds the list of currently selected items.checkedItems
maps each item to its checkbox state (true or false).- Adding an item: sets the item as checked and adds to
values
. - Toggling a checkbox: updates both the checkbox map and the main array.
- Removing: when an item is unchecked, it’s filtered out of
values
.
✨ Bonus Tip
Want to persist this list or send it to a backend? Just use the values
array — it's always in sync with checked items.
📦 Summary
This setup gives you a clean and controlled way to:
- Add items dynamically
- Toggle their inclusion via checkboxes
- Keep your UI and state perfectly in sync using TypeScript