Search code examples
javascriptreactjsfrontendstatereact-lifecycle

Child Component Not Being Rendered - React


I am going through a react course and currently learning react's lifecycle method. So far, I have been able to call the API using componentDidMount and have set the state. However, I can't seem to get the card components to show the images in the cardlist div. I'm sure I've done it correctly (looping through the state and creating a Card component with the props).

import react, {Component} from 'react';
import axios from 'axios';
import Card from './Card';
const api = ' https://deckofcardsapi.com/api/deck/';

class CardList extends Component {

    state = {
        deck: '',
        drawn: []
    }
    componentDidMount = async() => { 
        let response = await axios.get(`${api}new/shuffle`);
        this.setState({ deck: response.data })
    }

    getCards = async() => {
        const deck_id = this.state.deck.deck_id;
        let response = await axios.get(`${api}${deck_id}/draw/`);
         let card = response.data.cards[0];

         this.setState(st => ({
             drawn: [
                 ...st.drawn, {
                     id: card.code,
                     image: card.image,
                     name:  `${card.value} of ${card.suit}`
                 }
             ]
         }))
    }
    render(){
        const cards = this.state.drawn.map(c => {
            <Card image={c.image} key={c.id} name={c.name} />
        })
        return (
            <div className="CardList">
                 <button onClick={this.getCards}>Get Cards</button>
                 {cards}
            </div>
        )
    }
}

export default CardList;
import react, {Component} from 'react';

class Card extends Component {
    render(){
        return (
            
                <img src={this.props.image} alt={this.props.name} />
            
        )
    }
}

export default Card;
import CardList from './CardList';

function App() {
  return (
    <div className="App">
      <CardList />
    </div>
  );
}

export default App;

Solution

  • Your map function:

    const cards = this.state.drawn.map(c => {
        <Card image={c.image} key={c.id} name={c.name} />
    })
    

    does not return anything. So the result of this code is an array of undefined.

    You have two options:

    1. Add return:
    const cards = this.state.drawn.map(c => {
        return <Card image={c.image} key={c.id} name={c.name} />
    })
    
    1. Wrap in (), not {}:
    const cards = this.state.drawn.map(c => (
        <Card image={c.image} key={c.id} name={c.name} />
    ))