Home > front end >  How to put React hooks into for loop?
How to put React hooks into for loop?

Time:01-04

I want append a div container with divs. The divs quantity is the data json's length. I have tried to put the hooks inside the for loop, but it throwed error.

The project's github link: https://github.com/folza1/react-modulzaro

import "./App.css";
import React, { useEffect, useRef } from "react";

function App() {
  var data = require("./data.json");

  //for(let i=0;i<data.length;i  {WHAT COPY HERE TO APPEND THE 30 divProduct?})

  const container = useRef(null);

  const divProduct = document.createElement("div");
  divProduct.classList.add("divStyle");

  useEffect(() => {
    container.current.appendChild(divProduct);
  }, []);

  return (
    <div>
      <div id={"container"} ref={container} />
    </div>
  );
}
export default App;

CodePudding user response:

The example code posted seems somewhat confused with regards to how React works.

Assuming data is an array of objects, all you would need for this is something like the following:

import "./App.css";
import * as React from "react";

const data = [
  {id: "1", name: "obj1"}, 
  {id: "2", name: "obj2"},
  {id: "3", name: "obj3"}
];

function App() {
  return (
    <div id="container">
      {data.map(obj => <p key={obj.id}>{obj.name}</p>)}
    </div>
  );
}

export default App;

  • Related