In my app, I have a RoomsContainer
parent component, which has an array of Room
child components. In Room
, I want there to be a button to add additional Room
elements to the RoomsContainer
by calling the parent component's addRoom
function.
This is what I have:
function RoomsContainer() {
const [rooms, setRooms] = useState([]);
const addRoom = () => {
var uniqid = require('uniqid');
let key = uniqid("room-");
setRooms([
...rooms,
<Room
key={key}
id={key}
addRoom={addRoom}
removeRoom={removeRoom}
/>
]);
console.log(rooms);
}
useEffect(() => {
addRoom();
}, []);
// ...
return (
<div id="room-wrapper">
{rooms}
</div>
)
}
function Room(props) {
// ...
return (
<button onClick={props.addRoom}>
Add room
</button>
)
}
This adds the first room on page load, however when I click on the Add Room
button in the Room
component, it doesn't add any additional rooms. Clicking it also appears to re-render the entire RoomsContainer
component completely with a new Room
element instead of modifying its state. Also console.log(rooms)
always displays an empty array, even right after setting it.