import React from "react";
import ReactDOM from "react-dom";
import { createRoot } from 'react-dom/client';
import axios from "axios";
const BASEURL = "https://jsonplaceholder.typicode.com/users";
function axiosTest() {
return axios.get(BASEURL).then(response => response.data)
}
function stepTwo(){
axiosTest()
.then(data =>{
for (let i = 0; i < data.length; i ) {
console.log(data[i].name);
let nameElm = document.createElement("li");
let nameText = document.createTextNode(data[i].name);
let name2use = nameElm.appendChild(nameText)
document.getElementById("list4names").appendChild(name2use);
}
})
}
stepTwo();
function Component1(){
return(
<div>
<ol id = "list4names"></ol>
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Component1 />);
So, this program successful prints out all the times taken from the axios request. But what's strange is that even though I put them in an "ol" element with an "li" tag, they don't print in the style of a list. They all print on a single line, no bullets, no spaces between the items even. Why is this? I tried putting them in the div as p tags too, but there were similar (albeit not identical) results.
CodePudding user response:
Direct DOM manipulation like what you're doing is absolutely the wrong way to use React. React doesn't know you're modifying the DOM, so the next time it re-renders it's going to wipe out your changes. You don't get any benefit out of using React if you do this sort of thing, you may as well omit the framework if you're not going to use it.
Instead, once you've retrieved the data you need from the API, use React to do the rendering; that's what it's for:
return (
<div>
<ol id="list4names">
{data.map((item) => (<li>{item.name}</li>)}
</ol>
</div>
)
CodePudding user response:
You're not appending the li
that you've created to you're list; you're appending a textNode
.
let nameElm = document.createElement("li");
let nameText = document.createTextNode(data[i].name);
let name2use = nameElm.appendChild(nameText) // name2use is the appended textNode
document.getElementById("list4names").appendChild(name2use); // this appends a textNode to your list, not the li
nameElm.appendChild(nameText)
appends the nameText
textNode
to nameElm
and returns the newly appended node (the textNode
nameText
in this case).
You want to append nameElm
, the li
you have created, to your list instead:
let nameElm = document.createElement("li");
let nameText = document.createTextNode(data[i].name);
nameElm.appendChild(nameText); // append the textNode to the li
document.getElementById("list4names").appendChild(nameElm); // append the li to the list