Search code examples
reactjsrenderingreact-functional-component

Why is the content inside the curly braces not renderering in React.js


I have the following React functional component, but the content in curly braces doesn't render, where I am trying to show the user their past actions from the historyStack. The logic within these curly braces doesn't get executed and I don't understand why. I haven't used separate components, since I am just testing so far. Thanks in advance.

import React, {useState, useEffect} from 'react'
//import { getData } from '../shared/api'

const App = () => {
  useEffect(() => {
    let isMounted = true
    fetch('api/config.json')
        .then((response) => response.json())
        .then((config) => {
          isMounted && setInitData(config)
        })
    return () => { isMounted = false }
  }, [])

  const [historyStack, setHistoryStack] = useState([])
  const [initData, setInitData] = useState({})

  // Adds item to the history stack
  const handleClick = (item) => {
    setHistoryStack(historyStack.concat(item))
  }

  // Handles back action and removes the last item from the history stack
  const handleBack = () => {
    const updatedHistory = [...historyStack]
    updatedHistory.pop()
    setHistoryStack(updatedHistory)
  }

  // Load the inital data received from the API call
  const loadData = () => {
    setHistoryStack(historyStack.concat(initData))
  }

  const latestItem = historyStack[historyStack.length -1]

  return (
    <div>
      <h1>Produktfinder</h1>
      {
        !latestItem  && <button onClick={() => loadData()}>Start</button>
      }
      {        
        historyStack && historyStack.map((item, key) => {
          <p key={key}>{`${item.label}   -->`}</p>
      })}
      {
        latestItem && 
        <div>
          <h2>{latestItem.label}</h2>
          <p>{latestItem.question}</p>
        </div>
      }
      {
        latestItem && latestItem.children.map((item, key) => 
          <div key={key}>
            <button onClick={() => handleClick(item)}>{item.label}</button>
          </div>
        )
      }
      {   
       latestItem && <button onClick={() => handleBack()}>Zurück</button>
      }
    </div> 
  )
}

export default App

Solution

  • You're missing return statement in historyStack map. The following should work (given your conditions are right) :-

    historyStack && historyStack.map((item, key) => {
              return <p key={key}>{`${item.label}   -->`}</p>
          })
    

    The following will also work (Implicit return):

    historyStack && historyStack.map((item, key) => 
              <p key={key}>{`${item.label}   -->`}</p>
          )