I’m having problems on an old university exam.
Basically it asks to:
take this json file
[
{"colore": "#FF0080", "pos_orizz": 10, "pos_vert": 30},
{"colore": "#800080", "pos_orizz": 30, "pos_vert": 40},
{"colore": "#808000", "pos_orizz": 50, "pos_vert": 50},
{"colore": "#408080", "pos_orizz": 60, "pos_vert": 60},
{"colore": "#C0C0C0", "pos_orizz": 30, "pos_vert": 50}
]
create a function that, using the data contained in the json file, draws square divs in the "main" (the parent).
The dimensions of the divs are: 10% x 10% of the viewport;
position and background colour are specified in the json file (positions are in percentage of the size of the main)
I did everything but, of course, when i give my divs the style specs, the margin-top percentage is relative to the parent’s width…and that cause every sort of overflow problems
async function crea(){
const response = await MyFetch();
const main = document.querySelector("main");
response.forEach(element => {
let div = document.createElement("div");
div.style.width = "10vh";
div.style.height = "10vh";
div.style.backgroundColor = element.colore;
**div.style.marginTop = element.pos_vert+"%";**
div.style.marginLeft = element.pos_orizz+"%";
main.appendChild(div);
});
}
That’s my function and i know for sure there’s something i can do to make that work, i hope i’ve been clear in the exposition of the problem
2
Answers
createRoot(rootElement)
is a React utility function used to create a react root element, which is a DOM element in which UI components render themselves. It takes as a parameter the root element that should be created. This root element is not a React component, it is simply an empty div element that is used for React to render itself.So you should have an HTML file with empty div and
id="root"
in order to render the react page.This is an example snippet that demonstrates the CSS to use draw square divs on a parent div. In this demo I have set the position in CSS, but you will need to do this in JavaScript