S
S
StasUssov2020-10-04 18:50:24
React
StasUssov, 2020-10-04 18:50:24

How to display the nth number of items on the page, based on the number entered in the form?

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 them be squares) on the page and align them 5 in a row. For example, we enter 10 in the field and 10 items are displayed in two rows of 5.

What function would help with this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-10-04
@StasUssov

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/

N
Nikita Mikhailov, 2020-10-04
@Psixodelik

In state you enter a variable, with an initial value of null. When this number changes, you execute a function (which is initially set and makes sure that the value is not null), which draws the required number of elements.
Splitting elements by 5 is already easy. You can check in cycle. You can draw everything at once and position everything correctly with CSS

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question