jeudi 16 janvier 2020

How to randomly render an array of objects with React

I'm new to React and I'm having problems trying to render an object from an array through its id. I mean, I'm trying to generate a random number and compare this number with the id of an object from an array and render its full pack of items.

This is my App.js:

import React, {Component} from 'react';
import './App.css';
import RandomAlbums from './RandomAlbums';


class App extends Component {
  render(){
    const albums = [
      {id: 1, cover: './Covers/Disintegration.jpg', band: "The Cure", title: "Disintegration"},
      {id: 2, cover: './Covers/In_A_Silent_way.jpg', band: "Miles Davis", title: "In a Silent Way"},
      {id: 3, cover: './Covers/In_Rainbows.jpg', band: "Radiohead", title: "In Rainbows"},
      {id: 4, cover: './Covers/Laughing_Stock.jpg', band: "Talk Talk", title: "Talk Talk"},
      {id: 5, cover: './Covers/The_Mantle.jpg', band: "Agalloch", title: "Tha Mantle"}
  ]

    return (
      <div className="App">
        <RandomAlbums albums={albums} />
      </div>
    );
  }
}

export default App;

And this is my (not complete) RandomAlbum.js:

import React, {Component} from 'react';

class RandomAlbums extends Component {
    constructor(props) {
        super(props);
        this.state = {
            id: '',
            cover: '',
            band: '',
            title: ''
        };
    }


    getAlbum(albums){
      var random = Math.floor(Math.random() * 5);
      this.setState({id:random})
    }

  render(){
    return (
      <div>
        <button onClick={this.getAlbum}>Shuffle</button>
      </div>
    );
  }
}

export default RandomAlbums;

I just simply want to render a shuffle button, when onClick, I get a random cover whith its Band and Album title.

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire