How to create multiple React components dynamically using Hooks?

Asked

Viewed 155 times

0

I’m making an app on React which calculates compound interest and would like to know if anyone knows how to create several components at once dynamically.

Example: if I put 12 months I will have to generate 12 components of the type Box the amount, rate of increase and difference in the value of the initial amount. I’d like to call the component Box several times creating the boxes that would actually be divs with the information.

index.js:

useEffect(() => {
    var diference = 0;
    var variation = 0;
    var montante = 0;

    for (let counter = 1; counter <= period; counter++) {
      montante = initialCash * (1 + (tax / 100)) ** counter;
      diference = montante - initialCash;
      variation = diference / initialCash * 100;
      createBoxes(counter, period, montante, diference, variation);
      montante += diference;
    }

}, [initialCash, tax, period])

function createBoxes(c, p, m, d, v) {
    box = (
      <div className="card">
        <p> Mês: {c}</p>
        <p> Valor: {m}</p>
        <p> Diferença:{d}</p>
        <p> Variação:{v}</p>
      </div>
    );
    Box(box);
}

Box.js:

import React from 'react';

export default function Box(props) {
    //{ value } = props;
    console.log(props.box);
    return (
        <div>{props.box}</div>
    );
}
  • 1

    just create a listing or array state and when implementing this list automatically it creates the boxes, what their difficulty is?

  • When I run the code all are Undefined when they arrive at Box

1 answer

0

Proposing a example of creation of component as follows: will enter the value inside the box and by clicking the button Create several boxes will be created. This example is as simple as possible, but it practically demonstrates your doubts:

function Box({item}) {
  return <div className="box">{item.number}</div>
}

function App() {  
  const [count, setCount] = React.useState(0);
  const [items, setItems] = React.useState([]);
  const handleCreateBox = () => {
    const datas = [];
    for(let i = 0; i < count; i++) {
      datas[i] = {
        number: i + 1,
        description: `desc${i}` 
      }
    }
    setItems(datas);
  }
  return (
    <div>
      <div>
        <input 
             type="text" 
             value={count} 
             onChange={e => setCount(e.target.value)} 
        />
        <button 
          onClick={handleCreateBox}>Criar</button>
      </div>
      <div>
        {items.map((item, index) => <Box item={item} />)}
      </div>
    </div>
  )
}
ReactDOM.render(<App/>, document.getElementById('root'));
.box {
  height: 50px;
  width: 50px;
  border: 1px solid #333;
  margin: 6px;
  float: left;  
  justify-content: center;
  align-items: center;
  display: flex;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.