screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="app"></div> <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> <style> .container { max-width: 600px; margin: 0 auto; padding: 20px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); } .title { font-size: 24px; font-weight: bold; margin-bottom: 20px; } .list { list-style: none; padding: 0; } .list-item { font-size: 18px; margin-bottom: 10px; } .input-field { padding: 8px; font-size: 16px; border: 1px solid #ccc; border-radius: 4px; margin-bottom: 10px; } .add-button { padding: 8px 16px; font-size: 16px; background-color: #007bff; color: #fff; border: none; border-radius: 4px; cursor: pointer; } .add-button:hover { background-color: #0056b3; } </style> </body> </html>