Reputation: 8961
The result of a call to React.createElement(...)
is an object along the lines of:
{
$$typeof: Symbol(react.element),
key: null,
props: {children: Array(2)},
ref: null,
type: "div",
_owner: null,
_store: {validated: true},
_self: null,
_source: null,
__proto__: Object
}
I take this to be the representation of a DOM element in React's virtual DOM (please let me know if this is not correct).
Whilst creating functionality for dynamically adding elements to a page, I mistakingly tried by keeping an array of react elements in the state object:
class Form extends Component {
constructor(props) {
super(props)
this.state = { things: [], count: 0 }
}
updateForm(obj, cb) {...}
render() {
return (<>
{this.props.render({
updateForm: this.updateForm.bind(this),
...this.state
})}
</>)
}
}
const makeThing = props =>
<div>
I am a thing. count is: {props.count}
</div>
const App = () =>
<Form
render={
props => (
<div>
{props.things.map(t => t)} // RENDERING ELEMENTS DIRECTLY
<button onClick={() => props.updateForm({things: [...props.things, makeThing(props)]})}>Add thing</button>
<button onClick={() => props.updateForm({count: props.count + 1})}>Increase count</button>
</div>
)
} />
I have subsequently learned that specifying pre-created react elements as children of some component just isn't a good idea.
Why is it even possible? Surely there is NEVER a case when I would actually want to do this... I.e. it should error?
Upvotes: 0
Views: 537
Reputation: 9787
I can't see any problem with what you've posted. You're free to create your Components wherever and however you like and pass them around. They're just objects so they can go in state if you like.
The only caveat is that it's more efficient (and better in terms of separation of concerns) to pass around your viewData and handlers and then use that to render your components at the point when you actually need to.
Upvotes: 1