Reputation:
I have this code, inside of my code I am using a component, this should be possible?
let newBox = document.createElement("span")
for (let a = 0; a < suggestions.length; a++) {
let newDiv= <Option value={suggestions[a]}/>
newBox.appendChild(newDiv)
}
item.appendChild(newBox)
This component its only this:
import React, { useState } from 'react';
const Option = (value) => {
return (<div className="divBorder"> {value} </div>)
}
export default Option
Btw: I have this error in this part:newBox.appendChild(newDiv)
This is the error:
TypeError: Node.appendChild: Argument 1 does not implement interface Node.
Upvotes: 2
Views: 192
Reputation: 2341
incase you want to embed your react component array to that span you can use something like this
const newBox = document.createElement("span")
const embed = () => {
const itemsArray = []
for (let a = 0; a < suggestions.length; a++) {
itemsArray.push(<Option value={suggestions[a]}/>)
}
ReactDOM.render(itemsArray, newBox)
}
This was how old packages like hot-reload watched you component changes and re-fresh browser for changes.
But here is a react-ish way if you want
const NewBox = () => (
<span>
{suggestions.map(value => (
<Option value={value} />
))}
</span>
)
const Option = props =>
<div className="divBorder"> {JSON.stringify(props)} </div>
Upvotes: 1
Reputation: 19997
You need to understand how React’s JSX and “virtual DOM” work.
Things like <Option value={suggestions[a]} />
written in JSX, is eventually transpiled to JS, and the equivalent result is
React.createElement(Option, { value: suggestions[a] }, null)
Now you should see it’s impossible to append such a thing directly into DOM, it’s not even a valid DOM element!
It’s a React element, aka virtual DOM element, it’s meant to be consumed by a renderer engine that understands how to make sense of it. react-dom
lib is the engine for web platform, there can be other engine.
Upvotes: 3