Home > OS >  How to use map function with a number state
How to use map function with a number state

Time:10-14

I want to use map function with a number state. You guys already know that the map function works with arrays. But I want to use it with a number, not an array. Because I dont't want to create an array to use map function. And For loop is not works wll in jsx. So let's go to codes.

I'm defining the number state that I'm in a trouble:

const [pages, setPages] = useState(5)

Now, it's time to use map function. It's working with just a number:

[...Array(5)].map((page,i) => 
    <div>Page: {i 1}</div>
)

But it's not working with my number state that I defined before:

[...Array(pages)].map((page,i) => 
    <div>Page: {i 1}</div>
)

This is actually my biggest problem with the map function.

CodePudding user response:

You could use Array.from to properly create an Array instance and map over it to create array of pages.

Array.from({ length: pages }, (_, idx) =>
   <div>Page: {idx   1}</div>
)

const pages = 5;

const pagesArr = Array.from({ length: pages }, (_, idx) => idx   1);

console.log(pagesArr);

CodePudding user response:

Your code should work fine. Here is the live demo for the reference. Kindly check and try to find the root cause.

Live Demo :

const {useState} = React;

function Example() {
    
    const [pages, setPages] = useState(5);
    
    return (
        <div>
          <div>{[...Array(pages)].map((page,i) =>
            <div>Page: {i 1}</div>
          )}
          </div>
        </div>
    );
}

ReactDOM.render(
    <Example />,
    document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

  • Related