React validate if an item exist in array and set a message to the user

Hi, in this post I’m going to add a new item(name) to an existent array(names) and I will check if the new item exist in the array and if exist then send a message to the user in red color saying “Name is already in the list.” and if the new item doesn’t exist then add that name to the array.

View of the current array (names):

View after I inserted an existent name to the array:


// Dependencies
import { useState } from "react";

// Styles
import "./App.css";

function App() {
  // Local state
  const [names, setNames] = useState(["cristina", "victoria"]);
  const [newName, setNewName] = useState([""]);
  const [validation, setValidation] = useState(false);

  // Methods
  // Add new Name
  const handleOnClick = () => {
    const includeName = names.includes(newName);

    if (!includeName) {
      const newNames = [...names, newName];

  return (
      <section className="container">
        <h1>Names list:</h1>
        {, id) => {
          return (
            <section key={`id-${id}`}>
              <i className="fa-solid fa-trash-can" onClick={() => null}></i>

        {validation && (
          <section className="validation">Name is already in the list.</section>

          onChange={(e) => setNewName(}
        <button type="button" onClick={handleOnClick}>
          Add Name

export default App;

By Cristina Rojas.