How to display the n-th number of items on a page, based on the number entered into the form?

  • 0
    Good afternoon,

    while learning React and JS, the question arose:

    There is a page with a field for entering a number. After entering the number, you need to display the entered number of elements (any, let there be squares) on the page and align them 5 in a row. For example, we enter 10 in the field and 10 elements are displayed in two rows of 5.

    What function would help with this?

    Thank you in advance!
    JavaScript Jacob Woodard, Feb 13, 2019

  • 2 Answers
  • 0
    function App() {
    const [ count, setCount ] = useState(0);
    const onChange = e => setCount(Math.max(0, e.target.value | 0));

    return (
    <div>
    <input type="number" value={count} onChange={onChange} />
    <div className="container">
    {[...Array(count)].map((n, i) => <div className="item">{i}</div>)}
    </div>
    </div>
    );
    }


    https://jsfiddle.net/s6ho7bt0/
    Anonymous

  • 0
    In state, you enter a variable with an initial value of null. When this number changes, you execute the function (which is initially set and makes sure that the value is not null), which renders the required number of elements.



    Breaking down elements by 5 is already easy. You can check in a loop. You can render everything at once and position everything correctly with CSS
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!