Mapping an index from an array of strings

Viewed 288

I am trying to have a code that will return a random sentence from an array. Kind of like a random quote machine except it’s 3 different quotes on the page at the same time. Here’s how it looks

<div className="">
          {this.state.first.map((first) => (
            <div className="">{first}</div>
          ))}
        </div>
        <div className="">
          {this.state.second.map((second) => (
            <div className="">{second}</div>
          ))}
        </div>
        <div className="">
          {this.state.third.map((third) => (
            <div className="">{third}</div>
          ))}
        </div>

What I want to do is have the map function only return one from each array. I tried this by doing this.

 {this.state.first.map((first) => (
            <div className="">{first[0]}</div>
          ))} 

This gave me the first letter from each sentence. But what am I missing to have it give me the whole sentence returning instead of just the first letter? The whole code is viewable here https://github.com/Imstupidpleasehelp/CovidConspiracyGenerator/blob/master/src/Slotmachine.jsx Thank you in advance for your input.
Edit for clarification. I want to have a random index of each array display to the page when a user presses a button. I already have a function that will give me a random number between 1 and 10. I want to be able to have it work like a random quote machine.

1 Answers

Since you only want one element from the array of sentences, access one of the indicies of the .first, .second, .third arrays instead of trying to .map them. For example:

<div>{this.state.first[0]}</div>
<div>{this.state.second[0]}</div>
<div>{this.state.third[0]}</div>

More likely, you'd want to save the current index being displayed in state, and have something like:

<div>{this.state.first[this.state.firstIndex]}</div>
<div>{this.state.second[this.state.secondIndex]}</div>
<div>{this.state.third[this.state.thirdIndex]}</div>

where firstIndex will be a number from 0 to n - 1, where n is the length of this.state.first, and so on for the second and third. To select a new random quote in first, you'd do:

this.setState({
  ...this.state,
  firstIndex: Math.floor(Math.random() * this.state.first.length)
});
Related