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 [myArray, setMyArray] = useState([]); const [inputName, setInputName] = useState(''); const [inputAge, setInputAge] = useState(''); const addObjectToArray = () => { const newObj = { id: myArray.length + 1, name: inputName, age: inputAge }; setMyArray([...myArray, newObj]); setInputName(''); setInputAge(''); }; const handleNameChange = (event) => { setInputName(event.target.value); }; const handleAgeChange = (event) => { setInputAge(event.target.value); }; return ( <div className="container"> <h3>React Js Add Object to Array</h3> <div className='form-group'> <label>Name:</label> <input type="text" value={inputName} onChange={handleNameChange} /> </div> <div className='form-group'> <label>Age:</label> <input type="text" value={inputAge} onChange={handleAgeChange} /> </div> <button className='add-button' onClick={addObjectToArray}>Add Object</button> {myArray.map((obj) => ( <div className='table' key={obj.id}> <p className='row'>Name: {obj.name}</p> <p className='row'>Age: {obj.age}</p> </div> ))} </div> ); } ReactDOM.render(<App />, document.getElementById("app")); </script> <style> * { box-sizing: border-box; } .container { margin: 0 auto; width: 600px; text-align: center; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12), 0 2px 4px 0 rgba(0, 0, 0, 0.24); padding: 20px; } .form-group { margin-bottom: 20px; } label { font-size: 18px; font-weight: bold; margin-bottom: 5px; } input[type="text"] { padding: 10px; border-radius: 5px; border: 1px solid #ccc; width: 200px; font-size: 16px; } .add-button { padding: 10px 20px; border-radius: 5px; background-color: #4CAF50; color: #fff; border: none; font-size: 16px; cursor: pointer; transition: background-color 0.3s; } .add-button:hover { background-color: #45a049; } .table { background-color: #f5f5f5; padding: 10px; border-radius: 5px; margin-bottom: 10px; } .row { margin: 0; font-size: 16px; line-height: 1.5; } </style> </body> </html>