React: How to assign key based on state counter and increment state counter in mapping?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I'm building a react App that displays a list of items (the component name is 'el'). I would like each item to contain a unique key that is simply a counter (called 'rank' here) that the app increments for each item. I'm currently successfully assigning rank as the key in the mapping, but I don't know how to make to increment it so it's unique for each one. Is this possible? Should I use a for loop of some sort instead of map()?






class App extends Component {
constructor() {
super();
this.state = {
someList:[/*Some List of Elements*/],
rank:0,
};
}
render() {
const {myList, rank} = this.state;
return (
<section>
<div className="container-fluid">
<div className="row mb-5">
<div className="col">
<ul className="list-group" id="list">
{myList.map(
(el) => <AListElement id={el.id} text={el.text} key={rank}/>
)}
</ul>
</div>
</div>
</div>
</section>
}












share|improve this question





























    1















    I'm building a react App that displays a list of items (the component name is 'el'). I would like each item to contain a unique key that is simply a counter (called 'rank' here) that the app increments for each item. I'm currently successfully assigning rank as the key in the mapping, but I don't know how to make to increment it so it's unique for each one. Is this possible? Should I use a for loop of some sort instead of map()?






    class App extends Component {
    constructor() {
    super();
    this.state = {
    someList:[/*Some List of Elements*/],
    rank:0,
    };
    }
    render() {
    const {myList, rank} = this.state;
    return (
    <section>
    <div className="container-fluid">
    <div className="row mb-5">
    <div className="col">
    <ul className="list-group" id="list">
    {myList.map(
    (el) => <AListElement id={el.id} text={el.text} key={rank}/>
    )}
    </ul>
    </div>
    </div>
    </div>
    </section>
    }












    share|improve this question

























      1












      1








      1








      I'm building a react App that displays a list of items (the component name is 'el'). I would like each item to contain a unique key that is simply a counter (called 'rank' here) that the app increments for each item. I'm currently successfully assigning rank as the key in the mapping, but I don't know how to make to increment it so it's unique for each one. Is this possible? Should I use a for loop of some sort instead of map()?






      class App extends Component {
      constructor() {
      super();
      this.state = {
      someList:[/*Some List of Elements*/],
      rank:0,
      };
      }
      render() {
      const {myList, rank} = this.state;
      return (
      <section>
      <div className="container-fluid">
      <div className="row mb-5">
      <div className="col">
      <ul className="list-group" id="list">
      {myList.map(
      (el) => <AListElement id={el.id} text={el.text} key={rank}/>
      )}
      </ul>
      </div>
      </div>
      </div>
      </section>
      }












      share|improve this question














      I'm building a react App that displays a list of items (the component name is 'el'). I would like each item to contain a unique key that is simply a counter (called 'rank' here) that the app increments for each item. I'm currently successfully assigning rank as the key in the mapping, but I don't know how to make to increment it so it's unique for each one. Is this possible? Should I use a for loop of some sort instead of map()?






      class App extends Component {
      constructor() {
      super();
      this.state = {
      someList:[/*Some List of Elements*/],
      rank:0,
      };
      }
      render() {
      const {myList, rank} = this.state;
      return (
      <section>
      <div className="container-fluid">
      <div className="row mb-5">
      <div className="col">
      <ul className="list-group" id="list">
      {myList.map(
      (el) => <AListElement id={el.id} text={el.text} key={rank}/>
      )}
      </ul>
      </div>
      </div>
      </div>
      </section>
      }








      class App extends Component {
      constructor() {
      super();
      this.state = {
      someList:[/*Some List of Elements*/],
      rank:0,
      };
      }
      render() {
      const {myList, rank} = this.state;
      return (
      <section>
      <div className="container-fluid">
      <div className="row mb-5">
      <div className="col">
      <ul className="list-group" id="list">
      {myList.map(
      (el) => <AListElement id={el.id} text={el.text} key={rank}/>
      )}
      </ul>
      </div>
      </div>
      </div>
      </section>
      }





      class App extends Component {
      constructor() {
      super();
      this.state = {
      someList:[/*Some List of Elements*/],
      rank:0,
      };
      }
      render() {
      const {myList, rank} = this.state;
      return (
      <section>
      <div className="container-fluid">
      <div className="row mb-5">
      <div className="col">
      <ul className="list-group" id="list">
      {myList.map(
      (el) => <AListElement id={el.id} text={el.text} key={rank}/>
      )}
      </ul>
      </div>
      </div>
      </div>
      </section>
      }






      reactjs key






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 25 '18 at 5:20









      yalpsid emanyalpsid eman

      370721




      370721
























          2 Answers
          2






          active

          oldest

          votes


















          2














          The map() function comes with a unique index counter parameter for each item:



          {myList.map(
          (el, index) => <AListElement id={el.id} text={el.text} key={index}/>
          )}





          share|improve this answer































            0














            key attribute is for identifying the element uniquely. You don't have to maintain a state to pass to key.



            .map() method has index as the second param and you can pass it as a key as Shawn has mentioned in his answer. But generally, it's a good idea to append a unique string to the index and pass it to the key prop.



            {myList.map(
            (el, i) => <AListElement id={el.id} text={el.text} key={`el_${el.id}_${i}`}/>
            )}


            As to why it's important to not use just index as key prop




            key is the only thing React uses to identify DOM elements. What happens if you push an item to the list or remove something in the middle? If the key is same as before React assumes that the DOM element represents the same component as before. But that is no longer true.




            Here's an elaborate write-up with an example.



            Index as a key is an anti-pattern






            share|improve this answer
























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53464874%2freact-how-to-assign-key-based-on-state-counter-and-increment-state-counter-in-m%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              2














              The map() function comes with a unique index counter parameter for each item:



              {myList.map(
              (el, index) => <AListElement id={el.id} text={el.text} key={index}/>
              )}





              share|improve this answer




























                2














                The map() function comes with a unique index counter parameter for each item:



                {myList.map(
                (el, index) => <AListElement id={el.id} text={el.text} key={index}/>
                )}





                share|improve this answer


























                  2












                  2








                  2







                  The map() function comes with a unique index counter parameter for each item:



                  {myList.map(
                  (el, index) => <AListElement id={el.id} text={el.text} key={index}/>
                  )}





                  share|improve this answer













                  The map() function comes with a unique index counter parameter for each item:



                  {myList.map(
                  (el, index) => <AListElement id={el.id} text={el.text} key={index}/>
                  )}






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 25 '18 at 5:25









                  Shawn AndrewsShawn Andrews

                  975719




                  975719

























                      0














                      key attribute is for identifying the element uniquely. You don't have to maintain a state to pass to key.



                      .map() method has index as the second param and you can pass it as a key as Shawn has mentioned in his answer. But generally, it's a good idea to append a unique string to the index and pass it to the key prop.



                      {myList.map(
                      (el, i) => <AListElement id={el.id} text={el.text} key={`el_${el.id}_${i}`}/>
                      )}


                      As to why it's important to not use just index as key prop




                      key is the only thing React uses to identify DOM elements. What happens if you push an item to the list or remove something in the middle? If the key is same as before React assumes that the DOM element represents the same component as before. But that is no longer true.




                      Here's an elaborate write-up with an example.



                      Index as a key is an anti-pattern






                      share|improve this answer




























                        0














                        key attribute is for identifying the element uniquely. You don't have to maintain a state to pass to key.



                        .map() method has index as the second param and you can pass it as a key as Shawn has mentioned in his answer. But generally, it's a good idea to append a unique string to the index and pass it to the key prop.



                        {myList.map(
                        (el, i) => <AListElement id={el.id} text={el.text} key={`el_${el.id}_${i}`}/>
                        )}


                        As to why it's important to not use just index as key prop




                        key is the only thing React uses to identify DOM elements. What happens if you push an item to the list or remove something in the middle? If the key is same as before React assumes that the DOM element represents the same component as before. But that is no longer true.




                        Here's an elaborate write-up with an example.



                        Index as a key is an anti-pattern






                        share|improve this answer


























                          0












                          0








                          0







                          key attribute is for identifying the element uniquely. You don't have to maintain a state to pass to key.



                          .map() method has index as the second param and you can pass it as a key as Shawn has mentioned in his answer. But generally, it's a good idea to append a unique string to the index and pass it to the key prop.



                          {myList.map(
                          (el, i) => <AListElement id={el.id} text={el.text} key={`el_${el.id}_${i}`}/>
                          )}


                          As to why it's important to not use just index as key prop




                          key is the only thing React uses to identify DOM elements. What happens if you push an item to the list or remove something in the middle? If the key is same as before React assumes that the DOM element represents the same component as before. But that is no longer true.




                          Here's an elaborate write-up with an example.



                          Index as a key is an anti-pattern






                          share|improve this answer













                          key attribute is for identifying the element uniquely. You don't have to maintain a state to pass to key.



                          .map() method has index as the second param and you can pass it as a key as Shawn has mentioned in his answer. But generally, it's a good idea to append a unique string to the index and pass it to the key prop.



                          {myList.map(
                          (el, i) => <AListElement id={el.id} text={el.text} key={`el_${el.id}_${i}`}/>
                          )}


                          As to why it's important to not use just index as key prop




                          key is the only thing React uses to identify DOM elements. What happens if you push an item to the list or remove something in the middle? If the key is same as before React assumes that the DOM element represents the same component as before. But that is no longer true.




                          Here's an elaborate write-up with an example.



                          Index as a key is an anti-pattern







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 25 '18 at 5:41









                          Dinesh PandiyanDinesh Pandiyan

                          2,79811028




                          2,79811028






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53464874%2freact-how-to-assign-key-based-on-state-counter-and-increment-state-counter-in-m%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              這個網誌中的熱門文章

                              Tangent Lines Diagram Along Smooth Curve

                              Yusuf al-Mu'taman ibn Hud

                              Zucchini