0

I try to implement an component in my application. There i want to set the numbers of rendered paragraphs according to the numbers set by the user. For example if user selects 3 should appear 3 paragraphs, but if user after that select 1, the number of paragraphs should decrease to 1. This is my code:

const Nr = () => {
  const [nr, setNr] = useState([]);
  function onChange(value) {
    console.log("changed", value);
    setNr([...nr, value]);
  }

  return (
    <div>
      {nr.map(i => {
        return <p>{i}</p>;
      })}
      <InputNumber min={1} max={10} onChange={onChange} />;
    </div>
  );
};
export default Nr;

But now if select 3 the paragraphs are genereted ok, but if after that i select 2, the paragraphs does not decrease, but increase. How to solve this?
demo: https://codesandbox.io/s/cranky-glitter-9d7sn?file=/Number.js:163-490

3
  • I have checked your codesandbox, when I enter 3 there is only one line render with number 3, is it expected? Commented Jun 9, 2020 at 11:52
  • @TonyNguyen, no, thanks for this. It should be 3 paragraphs. Commented Jun 9, 2020 at 11:53
  • No need to use array in state variable Commented Jun 9, 2020 at 12:25

1 Answer 1

1

A good approach is to generate a new array using the incoming value (from the onChange function) as the array length.

Codesandbox: https://codesandbox.io/s/proud-http-r49px?file=/Number.js:163-526

const Nr = () => {
  const [nr, setNr] = useState([]);

  function handleInputChange(value) {
    const newArray = Array.from({ length: value }, (_, index) => index + 1);
    setNr(newArray);
  }

  return (
    <div>
      {nr.map(i => (
        <p key={i}>{i}</p>
      ))}
      <InputNumber min={1} max={10} onChange={handleInputChange} />;
    </div>
  );
};
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.