Laczkó Örs
Laczkó Örs

Reputation: 1118

How can I create react element in another?

I building a React app and I ran in the problem that how can I create react elements in another react element depending on the useState?

I created a somewhat simplified example:

import React, { useState } from 'react';
import Square from './square';

function Chart(props) {

    const [counter, setCounter] = useState(0);

    function increment() {
        setCounter++;
    }

    return (
        <div>
            <button onClick={increment()}>More squares</button>
            <div className="container">
                {
                    //I want to create as much <Square number={counter}/>  as the value of counter
                }
            </div>
        </div>
    );
}

export default Chart;

Upvotes: 0

Views: 94

Answers (3)

Auskennfuchs
Auskennfuchs

Reputation: 1737

You can have a look at lodash. There is a function times, which calls a function n-times.

import times from 'lodash/times'
...

function Chart(props) {

...
    return (
        <div>
            <button onClick={increment()}>More squares</button>
            <div className="container">
                {times(counter, idx => (<Square key={idx} number={counter}) ) />}
            </div>
        </div>
    );
}

You can also write this function on your own, if you don't want to import a whole library.

Upvotes: 1

Alexey  Baguk
Alexey Baguk

Reputation: 168

import React, { useState } from 'react';
import Square from './square';

export default function Chart(props) {

const [counter, setCounter] = useState(0);

function increment() {
    setCounter++;
}    

return (
    <div>
        <button onClick={increment()}>More squares</button>
        <div className="container">
            {
               createSquares(counter)
            }
        </div>
    </div>
  );
}

function createSquares(counter){
   const squares = [];
   while(counter){
     squares.push( <Square number={counter} key={counter}/> );
     counter--;
   }
   return squares;
}

Upvotes: 0

Nicholas Tower
Nicholas Tower

Reputation: 84912

Create an array of them. For example:

function Chart(props) {
    const [counter, setCounter] = useState(0);

    function increment() {
        setCounter(oldCounter => oldCounter + 1);
    }

    const squares = [];
    for (let i = 0; i < counter; i++) {
      squares.push(<Square number={i} key={i}/>)
    }

    return (
        <div>
            <button onClick={increment}>More squares</button>
            <div className="container">
                {squares}
            </div>
        </div>
    );
}

Upvotes: 1

Related Questions