import SingleInvite from "./SingleInvite";
imported a component that I created , but I keep getting [Object object] on the place of SingleInvite component
const newInvite = () => {
const container = document.querySelector(".container");
if (container) {
container.innerHTML += `${(<SingleInvite index={index} />)}`;
}
};
<div>
calling newInvite
<div className="container">
<SingleInvite index={0} />
</div>
<button className="add-another" onClick={newInvite}>
<img src={plus} className="plus" alt="" /> Add another
</button>
2
Answers
With React, you should avoid directly manipulating the DOM. It goes against all React principles.
Some documentation you might want to read up on: conditional rendering with React
It seems that you are trying to render the newInvite component in the container onClick. A better way would be:
In react, you should not be modifying the dom directly. Instead, have you’ll create one or more state variables, and change those states when you want to rerender. In your case since you want 1-N
<SingleInvite>
s, the most natural state is an array. I’m not sure what data you’ll need for each element of the array, so i’ll just give them a unique identifier.If you’re sure you’re not going to need any other data besides the number of invites, you could possibly get away with using a number as a state. Though most realworld examples have a little bit of complexity and so you’ll need to use the array approach as shown above.
Here’s an example with a number as the state: