'Array store the same value in React?
Code:
const [item, setItem] = useState([]);
const handleClick = (val, id) => {
setActiveIndex(id);
let text = val;
let index = id;
setItem([...item, { val: text, index: index }]);
// console.log("text", text);
};
Button code:-
<div>
{ChannelName.map((val, index) => {
return (
<div className="TextLink" key={index}>
<NavLink to={`/Table`}
onClick={(e) => myClick(val, index)} >
<button className='notActive buttonLeft'
onClick={() => { handleOnClick(index); handleClick(val, index) }} // pass the index
className={activeIndex === index ? "active" : "notActive"}>
{val}
</button>
</NavLink>
</div>
)
})
}
</div>
Tab div:-
<div className="allDivs">
{item.map((items, index) => {
console.log(item)
return (
<div key={index} >
<Test item={items} index={index} activeIndex={activeIndex} />
</div>
)
})}
</div>
When I click the Rundown List it's one time store but when I click the same value the second time it stores the same value How can I stop that value to store in the second click?
tab component:-
export default function Test({ item, index, activeIndex }) {
const [Close, setClose] = useState(true) // Every Child now has it's own setClose controll
return (
<Fragment>
<div id="CLOSEDIV" style={{ display: Close ? '' : 'none' }} className={activeIndex === index ? "activeTAB" : "tableHeaderBody"}>
<div className="TableText">
<div id="SHOW">{item.val}</div></div>
<div className="CloseIcon" id="CloseBtn"><FaRegTimesCircle style={{ color: "#FC0000", width: "10px", height: "10px", alignItems: "right" }} onClick={() => { setClose(false) }} /></div>
</div>
</Fragment>
)
Solution 1:[1]
Assuming your objective is to prevent adding an item into an array if it already exists & this needs to be implemented in the method: handleClick, please try if the below code-sample helps.
const handleClick = (val, id) => {
setItem(prev => {
if (prev.some(({index}) => (id === index))) return prev;
else return [...prev, {val, id}];
});
setActiveIndex(id);
};
Explanation
- Check if
prev(ie, previous value ofitemstate-variable - already has
someelement whereindexprop matchesid - If so, simply ignore the current event's
val,id - Else, append a new object with
valandidprops into the array - Update activeIndex (same as earlier case)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jsN00b |

