Neelasha Bhattacharjee
Neelasha Bhattacharjee

Reputation: 129

React components not conditionally rendering?

I am trying to build a simple website that will display a random lyric after the user selects a musical artist. I am struggling with making components appear on react after the button is clicked. It is likely that this is a really simple issue given I just started working with React yesterday and learned JS a few days ago. My first screen renders with the two artists and a button to chose between them, but I can't get anything past that to pop up. I also seem to be having trouble with the states not updating.


import axios from 'axios';
import React, {Component} from 'react'
import taylorSwift from './taylorswift.jpg';
import kanyeWest from './kanyewest.jpeg';

const TAYLOR_ID = "259675";
const KANYE_ID = "33091467";



class Game extends Component {
    constructor(props) {
        super(props);
        this.state = {
            artist_id: "",
            lyric: "", 
            actualTrack: "", 
            userTrack: "",
            artistSelected: false
        };
      }


    async getRandomLyric(artist_id) {
       const response = await axios.get(`http://localhost:3000/randomlyric/:${artist_id}`);
       this.setState({
        lyric :response.lyric, 
        actualTrack: response.actualTrack});
    }

    choseArtist(artist_id) {
         this.setState({
            artist_id: artist_id,
            artistSelected: true
        })

        return (
            <div>
            <p> Great! Now you a random lyric from the artist you chose will be presented and</p>
            <p> you will have to guess which song this lyric is from. </p> 
            <p> Good luck! </p>

            <div>
                {this.getRandomLyric(artist_id)}
                <p>What track is this lyric from: {this.state.lyric} </p>
                <input type = "text" onChange ={ (e) => {
                this.setState({userTrack: e.target.value})
                }}/>
            </div>
    </div>
    )
    
    }

   showLyrics (artist_id) {
        
   }


    render() {
    return (

        <div>
            <h1>Welcome to the Song Guessing Game!</h1> 
            <p> These are the rules of the game: </p>
            <p> First, you must pick whether you are Team Taylor or Team Kanye.</p>
            <p> After you pick your team, you will be presented with 5 random lyrics from your chosen artist.</p>
            <p> Your job is to guess which song each lyric is from. </p>
            <p> Good luck!</p>

            
            <div className = "team_taylor">
                <div>
                    <img className = "artist_picture"
                    src={taylorSwift} 
                    alt="Taylor Swift" />
                </div>

                <div className = "artist_button">
                    <button onClick={()=>{this.choseArtist(TAYLOR_ID); this.forceUpdate()}}> Team Taylor</button>
                </div>
                
            </div>
            

            <div className = "team_kanye">
                <div>
                    <img className = "artist_picture"
                    src={kanyeWest} 
                    alt="Kanye West"/>
                </div>
            
            <div className = "artist_button">
                <button onClick={()=>{this.choseArtist(KANYE_ID); this.forceUpdate()}}> Team Kanye</button>
            </div>
        </div>

    


    
            
        
        


    </div>

    );
        }
}

export default Game;

Upvotes: 0

Views: 45

Answers (1)

Miguel Hidalgo
Miguel Hidalgo

Reputation: 384

If you just started learning react I recommend you to learn React functional components and React hooks.

Here is an example of how your component would look like following the react functional components and hooks structure.

import { useEffect, useState } from "react";

const Game = () => {
  const [artist, setArtist] = useState({
    artist_id: "",
    lyric: false,
    actualTrack: "",
    userTrack: "",
    artistSelected: false
  });

  useEffect(() => {
   artist.artistSelected &&  axios
      .get(`http://localhost:3000/randomlyric/:${artist_id}`)
      .then((response) =>
        setArtist((prev) => ({
          ...prev,
          lyric: response.lyric,
          actualTrack: response.actualTrack
        }))
      )
      .catch(error => console.log(error));
  }, [artist.artistSelected]);

  return artist.lyric ? (
    <div>
      <p>
        {" "}
        Great! Now you a random lyric from the artist you chose will be
        presented and
      </p>
      <p> you will have to guess which song this lyric is from. </p>
      <p> Good luck! </p>

      <div>
        <p>What track is this lyric from: {artist.lyric} </p>
        <input
          type="text"
          onChange={(e) => {
            setArtist(prev => ({...prev, userTrack:e.target.value}))
          }}
        />
      </div>
    </div>
  ) : (
    <div>
      <h1>Welcome to the Song Guessing Game!</h1>
      <p> These are the rules of the game: </p>
      <p> First, you must pick whether you are Team Taylor or Team Kanye.</p>
      <p>
        {" "}
        After you pick your team, you will be presented with 5 random lyrics
        from your chosen artist.
      </p>
      <p> Your job is to guess which song each lyric is from. </p>
      <p> Good luck!</p>

      <div className="team_taylor">
        <div>
          <img
            className="artist_picture"
            src={taylorSwift}
            alt="Taylor Swift"
          />
        </div>

        <div className="artist_button">
          <button
            onClick={() =>
              setArtist((prev) => ({
                ...prev,
                artist_id: TAYLOR_ID,
                artistSelected: true
              }))
            }
          >
            {" "}
            Team Taylor
          </button>
        </div>
      </div>

      <div className="team_kanye">
        <div>
          <img className="artist_picture" src={kanyeWest} alt="Kanye West" />
        </div>

        <div className="artist_button">
          <button
            onClick={() =>
              setArtist((prev) => ({
                ...prev,
                artist_id: KANYE_ID,
                artistSelected: true
              }))
            }
          >
            {" "}
            Team Kanye
          </button>
        </div>
      </div>
    </div>
  );
};

export default Game;

Upvotes: 1

Related Questions