skip to Main Content

With the following prompt and correct answer how is the first item in the "show_1"

Render a list of shoe items in an ordered list and set the key attribute for each item to equal
"shoe_"" and the current number in the list. for example the first item in the list should have the key "shoe_1"

const shoes = ['flip flops', 'basketball shoes', 'tennis shoes'];

const shoeList = shoes.map((shoe, i) => (<li key={"shoe_"+i}>{shoeList}</li>);
<ol>{shoeList}</ol>

I don’t understand how the first item is shoes_1 if an index i would start at 0.

2

Answers


  1. The first element of a JavaScript array is not the 1st element, but the 0th element.

    Hence, if the expected behavior you want is for your iteration to print the first 0th element as 1, you should be doing i+1.

    Edit:

    key={"shoe_"+(i+1)}
    
    Login or Signup to reply.
  2. You should never use the index (i.e i) of the mapping as a key.

    Since they item (i.e. shoe) is a string, just use it directly.

    const { useEffect, useState } = React;
    
    const fetchShoes = Promise.resolve([
      "Flip flops",
      "Basketball shoes",
      "Tennis shoes",
    ]);
    
    const App = () => {
      const [shoes, setShoes] = useState([]);
    
      useEffect(() => {
        fetchShoes.then(setShoes);
      }, []);
    
      return (
        <ol>
          {shoes.map((shoe) => (
            <li key={shoe}>{shoe}</li>
          ))}
        </ol>
      );
    };
    
    ReactDOM.createRoot(document.getElementById("root")).render(<App />);
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search