dimanche 22 mai 2022

Use a random number to render that corresponding object ID's data in React

I'm trying to create an react app where you press a button and it gives you a date night option and a corresponding image. I created a small array of objects within dates.js ex:

export const dates = [
    {
        id: 0,
        name: "Comedy Club",
        image: "/assets/images/comic.jpg",   
    },
    {
        id: 1,
        name:"Piano Bar ",
        image: "/assets/images/piano-bar.jpg",
    }, 

Then I created a GetDates.js to use the random method & corresponding onclick event. Below is where I'm stuck. I've changed this code 100 times based on various previous answers and youtube tutorials but I receive errors or they are not exactly what I'm trying to render. Can you please let me know from this last update what is needed to display the dates.name & dates.image based on the randomId method used below? Again, I've altered this so much from my original attempt that I'm not sure this is the best approach. Any advice would be greatly appreciated!

class GetDates extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      image: "",
    };
  }

  randomSelect() {
    const randomId = dates[Math.floor(Math.random() * dates.length)].id;
    this.setState({ ...this.props.dates[randomId] });
  }

  render() {
    return (
      <div className="results-container">
        <button className="date-btn" onclick={this.randomSelect}>
          GET DATE IDEAS!
        </button>
      </div>
    );
  }
}

export default GetDates;



Aucun commentaire:

Enregistrer un commentaire