Home > Enterprise >  Display array elements with next and prev button using ReactJS
Display array elements with next and prev button using ReactJS

Time:11-02

I have an array which contains 10 objects, called emailThreads.

I am trying to display these objects with next and previous button but its not working as expected.

      <Controls>
        <Button onClick={previousEmail}>Previous Email</Button>
        <SubjectDetails>
          <Subject>SUBJECT</Subject>
          <SubjectTitle>{emailThreads[emailIndex].subject}</SubjectTitle>
          <SentAtDetails>Sent At {emailThreads[emailIndex].deliveredAt}</SentAtDetails>
        </SubjectDetails>
        <Button onClick={nextEmail}>Next Email</Button>
      </Controls>

this is code for previousEmail and nextEmail

  const [emailIndex, setEmailIndex] = useState(0);
  const previousEmail = () => {
    setEmailIndex((prevIndex) => {
      prevIndex !== 0 ? prevIndex - 1 : prevIndex;
    });
  };
  const nextEmail = () => {
    setEmailIndex((prevIndex) => {
      prevIndex !== emailThreads.length ? prevIndex   1 : prevIndex;
    });
  };

when I click on the next email,

TypeError: Cannot read properties of undefined (reading 'subject')

any help would be wonderful, thank you

CodePudding user response:

You can simply do this.

const previousEmail = () => {
    setEmailIndex(
      emailIndex !== 0 ? emailIndex - 1 : emailIndex;
    );
  };
  const nextEmail = () => {
    setEmailIndex(
      emailIndex !== emailThreads.length ? emailIndex   1 : emailIndex;
    );
  };

CodePudding user response:

seem like you're not returning anything inside setemailindex callback so changing your code to

 setEmailIndex((prevIndex) => prevIndex !== emailThreads.length ? prevIndex   1 : prevIndex);

or

setEmailIndex((prevIndex) => {
    retrun  prevIndex !== emailThreads.length ? prevIndex   1 : prevIndex;
    });

should work

CodePudding user response:

Be careful because you are comparing with length and not <= length - 2 (or < length - 1) so adding 1 to the current index will - at some point - cause an exception.

Use something like this

const nextEmail = () => {
    setEmailIndex(prevIndex => prevIndex < emailThreads.length - 1 ? prevIndex   1 : prevIndex);
}
  • Related