Hello I am doing task app and when I click create button it shows me [object Object] instead of component
Here is App component file:
import React from 'react'
import Task from './Task.js'
function App() {
function createTask(){
const tasksList = document.querySelector(".tasksList")
tasksList.append(<Task />)
}
return (
<div className='app'>
<div id='mainPanel'>
<button onClick={createTask}>create</button>
</div>
<div className='tasksList'>
</div>
</div>
)
}
export default App
Here is Task component file:
import React from 'react'
function Task() {
return (
<div>
<input/>
<button>delete</button>
</div>
)
}
export default Task
2
Answers
ReactJS uses what’s called a virtual DOM what this means in this case is that you can’t use a
ReactNode
(what gets returned from JSX expressions) as if it were anHTMLElement
. The correct way to do this is as follows:basically create some state and instead of trying to manipulate the dom directly, update the state.
As a side note, the code you had above could work in frameworks without a virtual DOM, for instance here is it working in SolidJS but even then I wouldn’t recommend this approach because it is going to be difficult to keep track of your state and mostly defeats the point of using a declarative framework.
the problem is that you’re trying to insert a JSX component into the DOM but this is impossible.
If you’re objective is to have a list of tasks and have a button to add a task into the list you can use the code below.
This code contains a react state, which is an array of tasks. By default, this array is empty.
When you click on the button to add a task, we use the setState function to add an object in the array ({name: "New task"}).
And then in the code, to render all the tasks that are in the array, we just map the tasks.