Strange behaviour when removing item from state array












0















I have an array in state which contains various components. When I click the remove button on one of the components, it removes the first item from the array instead. I only seem to have this problem when using components in the array, it works fine with an array of strings.



Parent component:



addItem = (block) => {
const add = [...this.state.items, block];
this.setState({items: add})
}

removeItem = (index) => {
const remove = [...this.state.items];
remove.splice(index, 1);
this.setState({items: remove})
}

render(){
return(
<div className="Board">
<div className="BoardContainer">
{this.state.items.map((item, index) => { return <Item remove= {this.removeItem} key={index} >{item}</Item>})}
</div>
<button onClick={() => this.addItem(<BannerImage />)}>Banner Image</button>
<button onClick={() => this.addItem(<ShortTextCentered />)}>Short Text Centered</button>
</div>
)
}


Child component:



export class Item extends React.Component {

handleRemove = () => {
this.props.remove(this.props.index)
}

render() {
return (
<div className="item">
{this.props.children}
<button onClick={this.handleRemove} >Remove</button>
</div>
)
}
}









share|improve this question





























    0















    I have an array in state which contains various components. When I click the remove button on one of the components, it removes the first item from the array instead. I only seem to have this problem when using components in the array, it works fine with an array of strings.



    Parent component:



    addItem = (block) => {
    const add = [...this.state.items, block];
    this.setState({items: add})
    }

    removeItem = (index) => {
    const remove = [...this.state.items];
    remove.splice(index, 1);
    this.setState({items: remove})
    }

    render(){
    return(
    <div className="Board">
    <div className="BoardContainer">
    {this.state.items.map((item, index) => { return <Item remove= {this.removeItem} key={index} >{item}</Item>})}
    </div>
    <button onClick={() => this.addItem(<BannerImage />)}>Banner Image</button>
    <button onClick={() => this.addItem(<ShortTextCentered />)}>Short Text Centered</button>
    </div>
    )
    }


    Child component:



    export class Item extends React.Component {

    handleRemove = () => {
    this.props.remove(this.props.index)
    }

    render() {
    return (
    <div className="item">
    {this.props.children}
    <button onClick={this.handleRemove} >Remove</button>
    </div>
    )
    }
    }









    share|improve this question



























      0












      0








      0


      1






      I have an array in state which contains various components. When I click the remove button on one of the components, it removes the first item from the array instead. I only seem to have this problem when using components in the array, it works fine with an array of strings.



      Parent component:



      addItem = (block) => {
      const add = [...this.state.items, block];
      this.setState({items: add})
      }

      removeItem = (index) => {
      const remove = [...this.state.items];
      remove.splice(index, 1);
      this.setState({items: remove})
      }

      render(){
      return(
      <div className="Board">
      <div className="BoardContainer">
      {this.state.items.map((item, index) => { return <Item remove= {this.removeItem} key={index} >{item}</Item>})}
      </div>
      <button onClick={() => this.addItem(<BannerImage />)}>Banner Image</button>
      <button onClick={() => this.addItem(<ShortTextCentered />)}>Short Text Centered</button>
      </div>
      )
      }


      Child component:



      export class Item extends React.Component {

      handleRemove = () => {
      this.props.remove(this.props.index)
      }

      render() {
      return (
      <div className="item">
      {this.props.children}
      <button onClick={this.handleRemove} >Remove</button>
      </div>
      )
      }
      }









      share|improve this question
















      I have an array in state which contains various components. When I click the remove button on one of the components, it removes the first item from the array instead. I only seem to have this problem when using components in the array, it works fine with an array of strings.



      Parent component:



      addItem = (block) => {
      const add = [...this.state.items, block];
      this.setState({items: add})
      }

      removeItem = (index) => {
      const remove = [...this.state.items];
      remove.splice(index, 1);
      this.setState({items: remove})
      }

      render(){
      return(
      <div className="Board">
      <div className="BoardContainer">
      {this.state.items.map((item, index) => { return <Item remove= {this.removeItem} key={index} >{item}</Item>})}
      </div>
      <button onClick={() => this.addItem(<BannerImage />)}>Banner Image</button>
      <button onClick={() => this.addItem(<ShortTextCentered />)}>Short Text Centered</button>
      </div>
      )
      }


      Child component:



      export class Item extends React.Component {

      handleRemove = () => {
      this.props.remove(this.props.index)
      }

      render() {
      return (
      <div className="item">
      {this.props.children}
      <button onClick={this.handleRemove} >Remove</button>
      </div>
      )
      }
      }






      javascript arrays reactjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 25 '18 at 21:45









      zeduke

      8518




      8518










      asked Nov 25 '18 at 18:09









      George BleasdaleGeorge Bleasdale

      436




      436
























          2 Answers
          2






          active

          oldest

          votes


















          1














          You used inside your component 'this.props.index' but you didn't pass the index to your component.



          you should do something like this:



          {this.state.items.map((item, index) => { return <Item remove={this.removeItem} key={index} index={index} >{item}</Item>})}





          share|improve this answer































            0














            Array.prototype.splice() mutates the array, so it's better not to use splice() with React.



            Easiest to use Array.prototype.filter() to create a new array.



            Furthermore working with unique id's rather than indexes prevents from unexpected results.



            let filteredArray = this.state.item.filter(x=> x!== e.target.value)
            this.setState({item: filteredArray});





            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%2f53470407%2fstrange-behaviour-when-removing-item-from-state-array%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









              1














              You used inside your component 'this.props.index' but you didn't pass the index to your component.



              you should do something like this:



              {this.state.items.map((item, index) => { return <Item remove={this.removeItem} key={index} index={index} >{item}</Item>})}





              share|improve this answer




























                1














                You used inside your component 'this.props.index' but you didn't pass the index to your component.



                you should do something like this:



                {this.state.items.map((item, index) => { return <Item remove={this.removeItem} key={index} index={index} >{item}</Item>})}





                share|improve this answer


























                  1












                  1








                  1







                  You used inside your component 'this.props.index' but you didn't pass the index to your component.



                  you should do something like this:



                  {this.state.items.map((item, index) => { return <Item remove={this.removeItem} key={index} index={index} >{item}</Item>})}





                  share|improve this answer













                  You used inside your component 'this.props.index' but you didn't pass the index to your component.



                  you should do something like this:



                  {this.state.items.map((item, index) => { return <Item remove={this.removeItem} key={index} index={index} >{item}</Item>})}






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 25 '18 at 18:18









                  Tom MendelsonTom Mendelson

                  55439




                  55439

























                      0














                      Array.prototype.splice() mutates the array, so it's better not to use splice() with React.



                      Easiest to use Array.prototype.filter() to create a new array.



                      Furthermore working with unique id's rather than indexes prevents from unexpected results.



                      let filteredArray = this.state.item.filter(x=> x!== e.target.value)
                      this.setState({item: filteredArray});





                      share|improve this answer






























                        0














                        Array.prototype.splice() mutates the array, so it's better not to use splice() with React.



                        Easiest to use Array.prototype.filter() to create a new array.



                        Furthermore working with unique id's rather than indexes prevents from unexpected results.



                        let filteredArray = this.state.item.filter(x=> x!== e.target.value)
                        this.setState({item: filteredArray});





                        share|improve this answer




























                          0












                          0








                          0







                          Array.prototype.splice() mutates the array, so it's better not to use splice() with React.



                          Easiest to use Array.prototype.filter() to create a new array.



                          Furthermore working with unique id's rather than indexes prevents from unexpected results.



                          let filteredArray = this.state.item.filter(x=> x!== e.target.value)
                          this.setState({item: filteredArray});





                          share|improve this answer















                          Array.prototype.splice() mutates the array, so it's better not to use splice() with React.



                          Easiest to use Array.prototype.filter() to create a new array.



                          Furthermore working with unique id's rather than indexes prevents from unexpected results.



                          let filteredArray = this.state.item.filter(x=> x!== e.target.value)
                          this.setState({item: filteredArray});






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 25 '18 at 18:26

























                          answered Nov 25 '18 at 18:21









                          Ole EH DufourOle EH Dufour

                          1,11911122




                          1,11911122






























                              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%2f53470407%2fstrange-behaviour-when-removing-item-from-state-array%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







                              Popular posts from this blog

                              Costa Masnaga

                              Fotorealismo

                              Sidney Franklin