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:

Code:

// 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);
    setValidation(includeName);

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


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

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

        <input
          className="add"
          type="text"
          name="name"
          onChange={(e) => setNewName(e.target.value)}
        />
        <button type="button" onClick={handleOnClick}>
          Add Name
        </button>
      </section>
    </body>
  );
}

export default App;

By Cristina Rojas.