Reputation: 96614
newbie
I can create an element but how do I then add to that element ?
When I try
<body>
React....
<div id="main_insert">
<span>
</span>
</div>
<script src="https://unpkg.com/[email protected]/dist/react.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script> <script>
let dish = React.createElement("h1", {id: 'top'}, "Baked Salmon");
let ingredients = React.createElement("ul", {id: 'mainList'},
React.createElement("li", null, "eggs"),
React.createElement("li", null, "ham"),
React.createElement("li", null, "spam")
);
ReactDOM.render(dish, document.getElementById('main_insert'));
ReactDOM.render(ingredients, document.getElementById('top'));
// react and js code here
</script>
</body>
I get the ingredients but not the dish
My H1 does exist, but content is gone
Upvotes: 1
Views: 1749
Reputation: 753
Note : This is more of an analysis of the issue, @Piotr has already provided a workaround.
From Reacts Website
ReactDOM.render()
controls the contents of the container node you pass in. Any existing DOM elements inside are replaced when first called
Lets look at the sequence of actions now:
1) No render
methods of the code are called ( both commented ):
Here, we can see that the child span
tag is getting displayed.
2) Now, we call the method ReactDOM.render(dish, document.getElementById('main_insert'));
This should insert the h1
element while replacing the existing child elements.
As expected, the child span
tag gets replaced with the h1
that we created.
3) Similarly, now when we call ReactDOM.render(ingredients, document.getElementById('top'));
, our new container node is the h1
tag. Thus any content within h1
gets replaced by the new element that we render within it like so :
Upvotes: 1
Reputation: 1688
Please take a look a this reworked example - should work:
<body>
React....
<div id="main_insert">
<span>
</span>
</div>
<script src="https://unpkg.com/[email protected]/dist/react.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script>
let ingredients = React.createElement("ul", {id: 'mainList'},
React.createElement("li", null, "eggs"),
React.createElement("li", null, "ham"),
React.createElement("li", null, "spam"));
let dish = React.createElement("h1", {id: 'top'},
"Baked Salmon",
ingredients);
ReactDOM.render(dish, document.getElementById('main_insert'));
// react and js code here
</script>
</body>
Upvotes: 1