React Js Check Element Already Exist in Array if not Add
React Js Check Element Already Exist In Array If Not Add - : In ReactJS, to check if an element already exists in an array, you can use the Array.prototype.includes()
method or the Array.prototype.indexOf()
method. If the element is not present, you can add it using Array.prototype.push()
, the spread operator, or Array.prototype.concat()
. This allows you to efficiently manage array data and avoid duplicates in your React components




Thanks for your feedback!
Your contributions will help us to improve service.
How can I check if an element exists in an array using Reactjs?
This React JS code creates a simple web application that allows users to add elements to an array and checks if the element already exists before adding. It utilizes the useState
hook to manage state variables. The function addElementIfNotExists
checks if the input value is not empty, converts the input value and array elements to lowercase, and then checks if the lowercase input value exists in the lowercase array using includes()
. If it already exists, an alert is shown. If not, the new element is added to a new copy of the array, and the state is updated. The current array elements are displayed in an unordered list, and an input field allows users to enter new elements. The "Add Element" button triggers the check and addition process.
React Js Check if an Element exists in an Array
<script type="text/babel">
const { useState } = React;
function App() {
const [arrayState, setArrayState] = useState(['Apple', 'Banana', 'Grapes']);
const [inputValue, setInputValue] = useState('');
const addElementIfNotExists = () => {
// Check if the inputValue is not empty
if (inputValue.trim() !== '') {
// Convert the inputValue and all elements in the array to lowercase
const lowercaseInputValue = inputValue.toLowerCase();
const lowercaseArray = arrayState.map(element => element.toLowerCase());
// Check if the lowercaseInputValue exists in the lowercaseArray
if (lowercaseArray.includes(lowercaseInputValue)) {
// If it already exists, show an alert
alert(`Element "${inputValue}" already exists in the array.`);
} else {
// If it doesn't exist, add it to a new copy of the array
const newArray = [...arrayState, inputValue];
// Update the state with the new array
setArrayState(newArray);
// Clear the input field after adding the element
setInputValue('');
}
}
};
return (
<div className='container'>
<h1 className='title'>Check if an Element exists in an Array in React</h1>
<ul className='list'>
{arrayState.map((element, index) => (
<li key={index} className='list-item'>{element}</li>
))}
</ul>
<input
type="text"
className='input-field'
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Enter an element"
/>
<button className='add-button' onClick={addElementIfNotExists}>Add Element</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>