screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script> <script src="https://unpkg.com/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 [objects, setObjects] = useState([]); const [inputValues, setInputValues] = useState({ name: '', age: '' }); const addObject = (e) => { e.preventDefault(); // create a new object with input values const newObj = { name: inputValues.name, age: inputValues.age }; // add the object to the array setObjects([...objects, newObj]); // clear the input fields setInputValues({ name: '', age: '' }); }; const handleInputChange = (e) => { const { name, value } = e.target; setInputValues({ ...inputValues, [name]: value }); }; return ( <div className='container'> <h3>React Js Create Array of object Dynamically | push item to array of object </h3> <form onSubmit={addObject}> <div> <label>Name:</label> <input type='text' name='name' value={inputValues.name} onChange={handleInputChange} required /> </div> <div> <label>Age:</label> <input type="number" name="age" value={inputValues.age} onChange={handleInputChange} required /> </div> <div> <button type="submit">Add Object</button> </div> </form> <ul> {objects.map((obj, index) => ( <li key={index}> Object {index + 1} - Name: {obj.name}, Age: {obj.age} </li> ))} </ul> </div> ); } ReactDOM.render(<App />, document.getElementById("app")); </script> <style> .container { text-align: center; padding: 20px; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12), 0 2px 4px 0 rgba(0, 0, 0, 0.24); margin: 0 auto; max-width: 600px; } h3 { margin-top: 0; font-size: 20px; color: #333; } form { margin-bottom: 20px; } label { display: block; margin-bottom: 5px; font-size: 16px; color: #555; } input[type="number"], input[type="text"] { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; } button[type="submit"] { padding: 10px 20px; background-color: #4caf50; border: none; border-radius: 4px; color: #fff; font-size: 16px; cursor: pointer; } button[type="submit"]:hover { background-color: #45a049; } ul { list-style: none; padding: 0; } li { margin-bottom: 5px; font-size: 16px; color: #555; } li:before { content: "▸"; margin-right: 5px; color: #4caf50; } </style> </body> </html>