const [checkedList, setCheckedList] = useState<string[]>([]);
const listData = [
{ id: "1", value: "Javascript" },
{ id: "2", value: "Python" },
{ id: "3", value: "Java" },
{ id: "4", value: "Kotlin" },
{ id: "5", value: "Dart" },
{ id: "6", value: "C#" },
];
const handleSelect = (event) => {
const value = event.target.value;
const isChecked = event.target.checked;
if (isChecked) {
setCheckedList([...checkedList, value]);
} else {
const filteredList = checkedList.filter((item) => item !== value);
setCheckedList(filteredList);
}
};
{checkedList.map((item, index) => {
return (
<div className="chip">
<p className="chip-label">{item}</p>
</div>
);
})}
{listData.map((item, index) => {
return (
<div key={item.id} className="checkbox-container">
<input
type="checkbox"
name="languages"
value={item.value}
onChange={handleSelect}
/>
<label>{item.value}</label>
</div>
);
})}
import React, {useState, useEffect} from 'react';
function SuperComponent() {
// хранилище для пунктов
const [checkedLanguages, setCheckedLanguages] = useState([]);
const [displayData, setDisplayData] = useState([]);
const languagesData = [
{ id: "1", name: "Javascript" },
{ id: "2", name: "Python" },
{ id: "3", name: "Java" },
{ id: "4", name: "Kotlin" },
{ id: "5", name: "Dart" },
{ id: "6", name: "C#" }
];
// фильтруем пункты
useEffect(() => {
if (checkedLanguages.length > 0) {
const newData = languagesData.filter(language => checkedLanguages.includes(language.name));
setDisplayData(newData);
} else {
setDisplayData(languagesData);
}
}, [checkedLanguages]);
function handleCheckboxChange(event) {
const languageName = event.target.value;
if (event.target.checked) {
setCheckedLanguages([...checkedLanguages, languageName]);
} else {
const newCheckedLanguages = checkedLanguages.filter(language => language !== languageName);
setCheckedLanguages(newCheckedLanguages);
}
}
return (
<div>
{checkedLanguages.map(language => (
<div key={language} className="selected-language">
<p>{language}</p>
</div>
))}
{languagesData.map(language => (
<div key={language.id} className="checkbox-wrapper">
<input
type="checkbox"
value={language.name}
onChange={handleCheckboxChange}
/>
<label>{language.name}</label>
</div>
))}
// отображаем отфильтрованные пункты
<div className="languages-list">
{displayData.map(language => (
<div key={language.id}>
{language.name}
</div>
))}
</div>
</div>
);
}
export default SuperComponent;